7

In some code I saw recently there was a structure defined like this:

typedef struct tagMyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;

The way I understand this, tagMyStruct is the new data type and MYSTRUCT is a variable that is created right there.

At another place, this was used like this:

MYSTRUCT *pStruct = new MYSTRUCT;

and it compiled fine with Visual Studio 2010. How is that valid C++? I thought MYSTRUCT was a variable and not a type?

bastibe
  • 16,551
  • 28
  • 95
  • 126

3 Answers3

9

No. tagMyStruct is the name of the struct. In C, unlike C++, you must explicitly use the struct keyword every time you use the struct type. For example

tagMyStruct x; //error
struct tagMyStruct x; //OK

To avoid writing struct all the time, struct tagMyStruct is typedef'd to MYSTRUCT. Now you can write

MYSTRUCT x; //ok, same as struct tagMyStruct x;

What you thought this was (a variable definition) would be without the typedef keyword, like this

struct tagMyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;

BTW

MYSTRUCT pStruct = new MYSTRUCT; //error cannot convert MYSTRUCT* to MYSTRUCT

is not valid C or C++ anyway. Maybe you mean

MYSTRUCT* pStruct = new MYSTRUCT; //valid C++ (invalid C - use malloc instead of new in C)

hth

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • 1
    @BastiBechtold: It isn't an ampersand. It is an asterisk. Ampersand is & :) – Armen Tsirunyan Dec 02 '10 at 11:58
  • Since when is 'new' valid in C? Also, it's worth emphasizing that this use of `typedef` is unnecessary and generally a bad idea in C++, exactly because C++ does not require you to use the `struct` keyword as part of the type name the way that C does. (Although sometimes you're stuck with it because you're inter-operating with legacy C code.) – Karl Knechtel Dec 02 '10 at 14:32
6
struct tagMyStruct { ... };

defines a new C++ type (class) called tagMyStruct.

struct { ... } MYSTRUCT;

defines a variable called MYSTRUCT with the given structure.

typedef struct { ... } MYSTRUCT;

defines a typedef called MYSTRUCT which is equivalent to the given anonymous struct.

typedef tagMyStruct struct { ... } MYSTRUCT;

defines a typedef called MYSTRUCT and a type called tagMyStruct. So MYSTRUCT is just a typedef for tagMyStruct. Therefore, MYSTRUCT pStruct defines a tagMyStruct called pStruct.

The assignment you gave is invalid, since new MYSTRUCT returns a pointer to MYSTRUCT.

Amnon
  • 7,652
  • 2
  • 26
  • 34
3

You are wrong, you are using typedef, i.e. MYSTRUCT is an alias for tagMyStruct. This explains how it's correct c++.

In order to create a variable, drop the typedef:

struct tagMyStruct {
    int numberOne;
    int numberTwo;
} MYSTRUCT;
Drakosha
  • 11,925
  • 4
  • 39
  • 52