Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this enum declaration a standard compliant?

Tags:

c++

c

enums

So normally enum's are for declaring group of "constant integers" as another type, that represents something. Eg.

enum Color {RED=0, BLUE, YELLOW};

This is clear. But recently I met following in code. This was in a compiler for embedded systems.

enum State {DISABLED=0, ENABLED=!DISABLED};

And it worked just fine. It behaved as a boolean type. My question is, wheather it (this syntax) is ANSI compliant?

If it is standard compliant, then why would compilers define internally something like _Bool for boolean representation and then in stdbool.h (for C language) they do:

#define bool _Bool
... // here goes definitions of true and false

instead of

enum bool {false=0, true=!false};

Which is much cleaner?

like image 446
DawidPi Avatar asked Oct 25 '15 22:10

DawidPi


People also ask

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

How do you declare an enum in C++?

It is used to assign names to the integral constants which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration. The following is the syntax of enums. enum enum_name{const1, const2, ....... };

What are enumeration variables How are they declared?

An enumeration type declaration gives the name of the (optional) enumeration tag. And, it defines the set of named integer identifiers (called the enumeration set, enumerator constants, enumerators, or members). A variable of the enumeration type stores one of the values of the enumeration set defined by that type.

What are enum types?

Enumerated (enum) types are data types that comprise a static, ordered set of values. They are equivalent to the enum types supported in a number of programming languages. An example of an enum type might be the days of the week, or a set of status values for a piece of data.


1 Answers

Yes, this is standard-compliant.

!DISABLED is a valid constant expression, which is all that is required for an enum value.

enum State {DISABLED=0, ENABLED= (!DISABLED)};
//                               ^^^^^^^^^^^

At the point where DISABLED is referenced, the compiler knows its value, so it can compute the value of the expression derived from it, i.e. !DISABLED. It is a fancy way of writing ENABLED=1.

like image 193
Sergey Kalinichenko Avatar answered Nov 15 '22 21:11

Sergey Kalinichenko