Home > Enterprise >  C - What underlying type would an enum with more than 18,446,744,073,709,551,616 elements have?
C - What underlying type would an enum with more than 18,446,744,073,709,551,616 elements have?

Time:09-08

This is more of a hypothetical question than a practical one. Of course there would be memory issues if we actually tried to compile a program with that large.

Enums in C will take on an underlying type to fit the maximum element of the enum. Also, if I specify no integer values, then each element is always 1 more than the previous starting at 0. So, for example, if I make an enum with 5 elements(or labels, however you call them) then it's type could be something like an int since that can fit the values 0,1,2,3,4.

The largest integral type in C is the long long, and an unsigned long long can take a value of up to 18,446,744,073,709,551,615. So what would happen if I made an enum with 18,446,744,073,709,551,616 elements? This would exceed the largest integral type, so it would need another type than long long.

What does the C spec have to say about this loophole?

CodePudding user response:

There's no loophole. You'll just get a diagnostic in a conforming compiler.

[dcl.enum]

7 ... If no integral type can represent all the enumerator values, the enumeration is ill-formed. ...

Or more practically, you'll get an error and compilation will halt.

It might even halt sooner, due to implementation defined limits, because that's a lot of enumerators.

  •  Tags:  
  • c
  • Related