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?
You are wrong, you are using
typedef
, i.e.MYSTRUCT
is an alias fortagMyStruct
. This explains how it's correct c++.In order to create a variable, drop the typedef:
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 exampleTo avoid writing struct all the time,
struct tagMyStruct
istypedef
'd toMYSTRUCT
. Now you can writeWhat you thought this was (a variable definition) would be without the typedef keyword, like this
BTW
is not valid C or C++ anyway. Maybe you mean
hth
defines a new C++ type (class) called
tagMyStruct
.defines a variable called
MYSTRUCT
with the given structure.defines a typedef called
MYSTRUCT
which is equivalent to the given anonymous struct.defines a typedef called
MYSTRUCT
and a type calledtagMyStruct
. So MYSTRUCT is just a typedef for tagMyStruct. Therefore,MYSTRUCT pStruct
defines atagMyStruct
calledpStruct
.The assignment you gave is invalid, since
new MYSTRUCT
returns a pointer toMYSTRUCT
.