Adam Martin
Adam Martin

Reputation: 1218

C++11 Casting enums to ints

I have a typed enum

enum side : int {_white=0,
                 _yellow=1,
                 _green=2,
                 _blue=3,
                 _red=4,
                 _orange=5};

However, using gcc-5, the compiler says it cannot use static_cast in the following scenario:

side value
function(static_cast<int *>(&value))

Why is that? Doing static_cast<int>(value)) does not raise any error.

Upvotes: 5

Views: 319

Answers (1)

Zan Lynx
Zan Lynx

Reputation: 54325

A pointer type cast is different than just a type conversion. Accessing through a pointer leaves the bytes the same but reads them differently. This is not safe for an enum because it can be different sizes of int.

A type conversion is safe though, because it converts the enum into an int as a copy. The original enum could be a single byte or two bytes but that doesn't matter once its copied into 4 or 8 bytes.

Upvotes: 5

Related Questions