c00000fd
c00000fd

Reputation: 22275

Form of enum without curly braces

I've witnessed today a form of enum that was written as such, compiled under VS 2017:

enum ens en1, en2, en3;

and then it was used as such:

int n = en2;

So my question is, what form of enum was it and why n was later set to 0?


Live example:

enum ens en1, en2, en3;

int main()
{
    int n = en2;
}

compiles without warning with the default compiler options

Upvotes: 5

Views: 765

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158479

This is non-conforming code, it is an extension as we can see if we use /Za MSVC also rejects the code.

We can see this is ill-formed from dcl.enum#2:

The enumeration type declared with an enum-key of only enum is an unscoped enumeration, and its enumerators are unscoped enumerators. The enum-keys enum class and enum struct are semantically equivalent; an enumeration type declared with one of these is a scoped enumeration, and its enumerators are scoped enumerators. The optional identifier shall not be omitted in the declaration of a scoped enumeration. The type-specifier-seq of an enum-base shall name an integral type; any cv-qualification is ignored. An opaque-enum-declaration declaring an unscoped enumeration shall not omit the enum-base. ...

This wording was added n2764 which allowed forward declaration of enums as long as the underlying type was specified.

For more details as to why we are not allowed to forward declare enums without an underlying type see Why must an enumeration's size be provided when it is forward declared?

Upvotes: 1

user7860670
user7860670

Reputation: 37548

This example is not correct because declaration of enum must either include underlaying type or a list of items. This also means that it can not be combined with variable declaration. fixed variant:

enum ens: int; // ens is a complete type at this point
enum ens en1, en2, en3; // en1 en2 en3 are global variables of enum ens type

// alternative "traditional" enum definition with empty list of items:
enum ens{} en1, en2, en3;

int n = en2; makes n equal to 0 because en2 is a global variable and is implicitly initialized with 0.

Upvotes: 4

Marcel
Marcel

Reputation: 1845

enum ens en1, en2, en3;

is no enum declaration. It is a variable declaration. It declares 3 variables of type enum ens. They are used in the code later.

At the assignment of

int n = en2;

the value of en2 happens to have an enum value that corresponds to the integer value 0.

Upvotes: 2

Related Questions