Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast invalid int value to enum

Tags:

c++

enums

Say I have

enum Foo { Foo0, Foo1, Foo2 };

Note that no explicitly declared Foo constant has the value 3 (they are 0, 1, and 2).

Does the following invoke undefined behavior?

Foo yay = (Foo) 3;

Note expecially that 3 might fit into the internal representation of Foo.

like image 900
Thomas Eding Avatar asked Dec 13 '12 22:12

Thomas Eding


1 Answers

It's well defined. In order to represent the value 0, 1, and 2, the type Foo has to have at least two bits, and that's enough to represent 3 as well.

like image 185
Pete Becker Avatar answered Nov 07 '22 12:11

Pete Becker