Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is empty enum ( enum{}; ) portable?

Tags:

c++

class Test
{
  enum{};
  ...
};

Is this empty enum definition portable? Compiles in gcc and and msvc.

like image 571
Alexander Vassilev Avatar asked Mar 20 '12 14:03

Alexander Vassilev


People also ask

Can you have an empty enum?

An ENUM can also contain NULL and empty values. If the ENUM column is declared to permit NULL values, NULL becomes a valid value, as well as the default value (see below).

Can you have an empty enum in Java?

Of course you can!

How do you know if an enum is empty?

First of all an Enum can't be empty! It is an Object representing a defined state. Think of it like an static final Object which can't be changed after intialization, but easyly compared. So what you can do is check on null and on Equals to your existing Enum Values.

How do you declare an empty enum in Java?

noneOf(Class<E> elementType) method creates an empty enum set with the specified element type.


2 Answers

According to the following snippet from the c++ standard we can deduce that it's indeed a valid statement:

7.2/1 Enumeration declarations (C++03)
...
enum-specifier:
       enum identifieropt { enumerator-listopt }

Note that both the identifier and the enumerator-list are optional, and therefor a statement as enum {} is valid (if you ask the standard).


But doesn't the standard also say that empty declarations are ill-formed?

Yes, and there is even an example of enum { }; in the below snippet from the standard.

7/3 Specifiers (C++03)

In these cases and whenever a class-specifier or enum-specifier is present in the decl-specifier-seq, the identifiers in these specifiers are among the names being declared by the declaration (as class- names, enum-names, or enumerators, depending on the syntax).

In such cases, and except for the declaration of an unnamed bit-field (9.6), the decl-specifier-seq shall introduce one or more names into the program, or shall redeclare a name introduced by a previous declaration.

*Example [

 enum { };          // ill-formed
 typedef class { }; // ill-formed

*end example]


Conclusion

The statement seems to be ill-formed after a careful look at the standard, though compilers are written by humans - and humans tend to make mistakes and sometimes overlook things.


TL;DR You should not use an empty declaration such as enum { };, even though it compiles

like image 186
Filip Roséen - refp Avatar answered Oct 20 '22 19:10

Filip Roséen - refp


such an enum is specifically listed in clause 7 paragraph 3 of the C++ standard as ill-formed. gcc does not accept it. there was a bug fix for this in gcc:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=29018

like image 41
WeaselFox Avatar answered Oct 20 '22 20:10

WeaselFox