Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any guarantees on the representation of large enum values?

Tags:

c++

c

enums

Suppose I have (on a 32 bit machine)

enum foo {     val1 = 0x7FFFFFFF, // originally '2^31 - 1'     val2,     val3 = 0xFFFFFFFF, // originally '2^32 - 1'     val4,     val5 }; 

what is the value of val2, val4 and val5? I know I could test it, but is the result standardized?

like image 296
Bathsheba Avatar asked Jun 11 '13 13:06

Bathsheba


People also ask

How big can an enum be?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

How many values can enum hold?

An ENUM column can have a maximum of 65,535 distinct elements. If you retrieve an ENUM value in a numeric context, the column value's index is returned.

How many bytes is a enum?

Answer. An enum is effectively a signed integer with a potential value range from -32768 to +32765. However, an enum can be stored in either one or two bytes, depending on what values are assigned to it.


1 Answers

In C standard:

C11 (n1570), § 6.7.2.2 Enumeration specifiers

Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

If the underlying type used by the compiler is not capable to represent these values, the behavior is undefined.

C11 (n1570), § 4. Conformance

If a ‘‘shall’’ or ‘‘shall not’’ requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined.

like image 151
md5 Avatar answered Sep 25 '22 02:09

md5