Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to define an unnamed struct?

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.

like image 963
Igor G Avatar asked Apr 30 '19 07:04

Igor G


People also ask

Can you define a structure without a name?

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.

What is an anonymous struct in C?

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.

Is a struct a definition or declaration?

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 ...

Can a struct have itself as a member?

A structure T cannot contain itself.


1 Answers

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).)

like image 67
L. F. Avatar answered Oct 09 '22 06:10

L. F.