C enumeration with 32-bit values

I need some unsigned 32-bit enum values ​​for my software, so I implemented this (simple) enum:

enum{ val1 = 0xFFFFFFFFu, val2 = 0xFFFFFFFEu, val3 = 0xFFFFFFF0 }; 

Problem: Each time I run the compiler, Eclipse interrupts the compilation and marks the enumeration with the following error:
enter image description here
In my oppinion, a value of 32 int should not be a problem for enums, but obviously it looks like. I would appreciate some data :)

[Update 1:] I will try to find the problem in the compiler settings, I will keep you posted

+5
source share
2 answers

The enumeration constant ( val1 in your example) must be of type int according to the C standard. This is a signed type and a 32-bit system, the value FFFFFFFF will not fit into it. Thus, this value will be converted to a signed integer in a specific concrete variant (specific to the compiler). If this is not done, you will get a signal defined by the implementation.

Writing code that relies on this is bad because it is not portable and unpredictable. There is no compiler setting that can fix this, because it is a language design.

I believe the gcc -pedantic / -pedantic-errors flag can be removed to get rid of the warning, but this is a bad idea since you will no longer follow the default C. gcc standard, the non-standard "skunk mode" -std=gnu90 or -std=gnu11 will compile code like any -std=cxx without -pedantic-errors .

This is why enumerations are unsuitable for any form of bitmasks or bitwise operations.

The best solution is to get rid of the enumeration and use either #define or const uint32_t , depending on what is most convenient for your specific scenario.

+4
source

Have you tried this ?:

 enum { val1 = (int)0xFFFFFFFFu, val2 = (int)0xFFFFFFFEu, val3 = (int)0xFFFFFFF0 }; 

Edit: I just installed gcc on cygwin and tried this.

test-enum.c is the original version of test-enum-int.c with explicit casting:

 $ cc -std=c11 -pedantic-errors -c test-enum.c test-enum.c:2:8: error: ISO C restricts enumerator values to range of 'int' [-Wpedantic] val1 = 0xFFFFFFFFu, ^ test-enum.c:3:8: error: ISO C restricts enumerator values to range of 'int' [-Wpedantic] val2 = 0xFFFFFFFEu, ^ test-enum.c:4:8: error: ISO C restricts enumerator values to range of 'int' [-Wpedantic] val3 = 0xFFFFFFF0u ^ $ cc -std=c11 -pedantic-errors -c test-enum-int.c 

(no complaints)

 $ cc --version cc (GCC) 5.4.0 Copyright (C) 2015 Free Software Foundation, Inc. 
+3
source

Source: https://habr.com/ru/post/1263616/


All Articles