Is the following code legal?:
struct
{
int x;
};
This code simply defines an unnamed structure. I do not intend to create objects of this type, nor do I need this structure in any other way. It simply appears in the source as a side effect of some complex macro expansion.
Useless though it is, I see no problem with it. Just another piece of code that can be compiled and then optimized out completely.
However, in the real world the outcome is quite different from my expectations:
GCC 8.3 reports an error:
error: abstract declarator '<unnamed struct>' used as declaration
Clang 8.0.0 reports an error too:
error: anonymous structs and classes must be class members
warning: declaration does not declare anything [-Wmissing-declarations]
Only MSVC 2017 sees no problem with such source.
So, the question is: who's right? Is there a relevant quote from the Standard that explicitly forbids such declarations?
Edit:
The project uses C++11. But the error messages are the same for C++98, C++11 and C++17.
Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions. Definition is just like that of a normal union just without a name or tag.
Anonymous structs A Microsoft C extension allows you to declare a structure variable within another structure without giving it a name. These nested structures are called anonymous structures. C++ does not allow anonymous structures.
A struct in the C programming language (and many derivatives) is a composite data type (or record) declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the ...
A structure T cannot contain itself.
No, it is not allowed. GCC and Clang are right.
Per [dcl.dcl]/3 (7 Declarations) in N3337 (C++11 final draft), a class declaration must introduce at one name to the program. For example, the following are invalid:
enum { };
typedef class { };
(Note: this isn't unique to C++11. In N4140 (C++14 final draft) it is [dcl.dcl]/5 (7 Declarations). In N4659 (C++17 final draft) it is [dcl.dcl]/5 (10 Declarations).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With