Reputation: 888
After I have defined an enum like this:
typedef enum { x = 1ULL<<40 } e;
it seems that the expression 'x' evaluates to 1UL<<40.
However, C11 6.4.4.3 says "An identifier declared as an enumeration constant has type int."
Incidentally this saves my day, since I want enum values > 1<<32. However, I need to know how this can be; I'm a bit nervous to write code that isn't standards compliant.
I tried this code:
int main() {
printf("%zu %zu %lx\n", sizeof(e), sizeof(x), x);
return 0;
}
Compiling with gcc -std=c11 -Wall
(gcc 8.3.1, linux x86_64), it outputs: 8 8 10000000000
.
If I change %lx to %llx, I get a compile warning and the same output, which indicates x is long-sized.
Based on my reading of the spec, I would expect compile warnings and output 4 4 0
.
Upvotes: 3
Views: 345
Reputation: 224964
Compiler extensions. For example, with clang:
$ CFLAGS=-Weverything make example && ./example
cc -Weverything example.c -o example
example.c:3:16: warning: ISO C restricts enumerator values to range of 'int'
(1099511627776 is too large) [-Wpedantic]
typedef enum { x = 1ULL<<40 } e;
^ ~~~~~~~~
1 warning generated.
8 8 10000000000
And with gcc:
$ CFLAGS='-Wall -pedantic' make example && ./example
cc -Wall -pedantic example.c -o example
example.c:3:20: warning: ISO C restricts enumerator values to range of ‘int’ [-Wpedantic]
typedef enum { x = 1ULL<<40 } e;
^~~~
8 8 10000000000
Upvotes: 3