Reputation: 1463
I compiled these codes in MSVC:
int a=sizeof(struct{char c;});
and
int b=((struct{char c;} *)0,0);
and
printf("%p",(struct{char c;} *)0);
As C codes, they can pass compiling, with a warning (warning c4116: unnamed type definition in parentheses. If you give a name, it's "warning c4115: "Whatever" : named type definition in parentheses");
As C++ codes, they are compiled with a bunch of errors.
My questions are:
1. In C, are type definitions in parentheses valid? Why do I get that warning?
2. In C++, are type definitions in parentheses valid?
EDIT :
3. Why?
Upvotes: 4
Views: 3276
Reputation: 157344
In C, sizeof
can be applied to any type-name that is not an incomplete type (6.5.3.4p1); a struct-or-union-specifier that contains a struct declaration list (6.7.2.1p1) is a type-specifier and thus a type-name. MSVC's warning is there for two reasons: first, because some older compilers (or a C++ compiler used as a C compiler) might not support this usage, and second, because it's unusual and might not be what you intended.
In C++, sizeof
can be applied to a type-id; a class-specifier is a type-specifier and thus a type-id, but a class specifier that defines a class (or an enum specifier that defines an enumeration) can only appear in a class declaration or a using
declaration (7.1.6p3). This is probably because C++ classes can have linkage and allowing them to appear in general expressions (not just definitions) would complicate this.
Upvotes: 5
Reputation: 145829
In C:
sizeof(struct{char c;})
and
sizeof((struct{char c;} *)0,0)
are both valid expressions. An implementation is free to issue an additional informational diagnostic messages for valid C code.
Upvotes: 3