Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Type definition in parentheses

I compiled these codes in MSVC:

int a=sizeof(struct{char c;});


int b=((struct{char c;} *)0,0);


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?

3. Why?

like image 208
zwhconst Avatar asked Mar 22 '23 15:03


1 Answers

In C, sizeof can be applied to any type-name that is not an incomplete type (; a struct-or-union-specifier that contains a struct declaration list ( 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.

like image 133
ecatmur Avatar answered Mar 24 '23 05:03