Thomas Eding
Thomas Eding

Reputation: 1

Cast invalid int value to enum

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.

Upvotes: 7

Views: 322

Answers (1)

Pete Becker
Pete Becker

Reputation: 76305

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.

Upvotes: 8

Related Questions