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?
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.
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, ....... };
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With