Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

No, they are forbidden by the standard (take a look at cppreference). Some compilers implement the C behavior as an extension, so tell your compiler to follow the standard strictly.

I don’t use extensions, even convenient ones, as I have to be able to run my code on a variety of compilers. If you don’t have to do that, some extensions (like this one) are really handy.



From the standard, the enum-name is marked as optional in the enum grammar: in [dcl.enum](https://eel.is/c++draft/dcl.enum#11) ; it is also referenced e.g. in [dcl.dcl]:

> An unnamed enumeration that does not have a typedef name for linkage purposes ([dcl.typedef]) and that has a first enumerator is denoted, for linkage purposes ([basic.link]), by its underlying type and its first enumerator; such an enumeration is said to have an enumerator as a name for linkage purposes.

And for classes/structs, [class.pre](https://eel.is/c++draft/class.pre#def:class,unnamed) has explicit wording:

> A class-specifier whose class-head omits the class-head-name defines an unnamed class.

So both are entirely fine (and likewise, unions are too).

Note that my links are for the current draft, but I just checked and this was already the case as far back as C++11. So I wonder where this persistent myth seems to come from.


This is awesome. I referenced cppreference, but that is not authoritative. Unfortunately, in the final draft, [class.pre] grammar makes the name mandatory even though the language you quote remains in the first textual paragraph following the grammar specification!

The part of enums you quoted was C-compatible enums; anonymous scoped enums are explicitly forbidden: "The optional enum-head-name shall not be omitted in the declaration of a scoped enumeration" (dcl.enum 2).

Sigh. I will send in a clarification at least on the class/struct/union side. Ideally the grammar would be fixed rather than that paragraph.

The draft I looked at is https://timsong-cpp.github.io/cppwp/n4868/ (2020-10-18, shortly after the standard was approved).


> Unfortunately, in the final draft, [class.pre] grammar makes the name mandatory even though the language you quote remains in the first textual paragraph following the grammar specification!

That's pretty strange, considering e.g. this paper for quite some time ago: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p022... which is written as if anonymous structs always were a thing.

I wonder if there isn't a deep confusion somewhere where "anonymous" and "unnamed" mean different things to different persons.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: