I'm not sure if it would be completely correct in standard C++, but I tested with g++ -pedantic -Wall
and got no errors or warnings (note that this doesn't necessarily mean it's completely standard. g++, even with -pedantic, doesn't go through the trouble of giving warning for all non standard code.) (Does someone know the c++ spec well enough to comment on whether it is actually standard or not?)
The thing with writing:
struct person person = {...};
is that in C++, person
both refers to the variable and to the type. In C, this wasn't a problem simply because person
is not the type (struct person
is). Although from the context, with the few tests I wrote with g++, the compiler had no problem understanding when I am asking for the variable and when for the type, I do think it might get confused at some point. One confusing thing that I discovered is that if you have:
struct person *person = ...;
then sizeof(person)
returns the size of the variable, while to get the size of the type, you should write sizeof(struct person)
which I can assure you, no c++ coder would remember to write the stuct
.
It is best to avoid all kinds of confusion. I usually do this for code that could be used both in C and C++:
typedef struct person
{
...
} person;
Giving a name to the struct that is being typedef
ed allows the programmer to use either person
or struct person
. So, a bit of flexibility (not to mention you don't have to change already written code after typedef
ing the struct
.