How many bits does enum matter?

#include <stdint.h>

enum state : uint8_t {
    NONE,
    USA,
    CAN,
    MEX
};

struct X {
    state st : 2;  // compiles with uint8_t st : 2
};

Clang 3.9.0 compiles successfully.

GCC 4.8.4 and 5.3.0 complain:

warning: ‘X::st’ is too small to hold all values of ‘enum state’

Who is right?

+4
source share
1 answer

TL DR

Both are correct.


The value of the enumeration is limited by the base type, not by counters!

C ++ 14, 7.2 Listing declarations, clause 8:

You can define an enumeration that has values ​​that are not defined by any of its counters.

This means that you can:

state x = static_cast< state >(5);

This is what GCC warns about: enum statemay have values ​​that do not fit into 2 bits.

However, until you try to do this with X::st, everything will be brilliant.

This is (possibly) why Klang does not warn you about this.

, .

+1

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


All Articles