5

Since I know each element of an enum has its own integer value, I tried this:

enum Foo {
    Red = 0,
    Blue = 1
};

int main(void) {
    enum Foo bar = 2;
    return 0;
}

And it... works. I looked further and I think it has the same minimum and maximum limits as int (I started experiencing UB after INT_MAX). At that point, isn't an enum no better than a set of #defines? I could also very well be wrong here, though.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33

1 Answers1

3

An enum variable is an integer with a type large enough for the largest value defined in the enum definition, not necessarily int and potentially larger than int on some compilers. You can store int it any other value compatible with the storage type, no check is performed at run time.

If you increase your compiler's warning level, (eg: gcc -Wall -Wextra or clang -Weverything) you might get a warning about the value being different from all defined enumeration constants for the target enum.

For example clang produces these warnings when invoked with -Weverything:

test.c:7:20: warning: integer constant not in range of enumerated type 'enum Foo' [-Wassign-enum]
    enum Foo bar = 2;
                   ^
test.c:7:14: warning: unused variable 'bar' [-Wunused-variable]
    enum Foo bar = 2;
chqrlie
  • 131,814
  • 10
  • 121
  • 189