4

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
Adam Martin
  • 1,188
  • 1
  • 11
  • 24
  • 2
    different types, shouldn't you use `reinpterpret_cast`? – Feng Wang Jul 10 '16 at 19:47
  • 5
    You can convert a bool to a double, but that doesn't mean that a bool pointer can be meaningfully treated as a double pointer. – Kerrek SB Jul 10 '16 at 19:48
  • I thought a typed enum was essentially the same datatype though? Since it's typed as an `int`, the compiler should be able to accept that `static_cast` no? Obviously using `reinterpret_cast` works, but it's a bit of a code smell. – Adam Martin Jul 10 '16 at 19:51
  • 6
    Yes, it's a code smell, but you're arguably trying to do something smelly. With `int* y`, you're allowed to do `*y = 44`. With `side* y`, you are not. You are removing a safety net. – zneak Jul 10 '16 at 19:57
  • @zneak... Thinking it through, it is smelly, makes sense. I think a combination of your commment and Kerrek's would be an answer, I didn't really think through the bounds. Not quite sure how to get rid of my code smell in my personal case though, probably going to have to stick with a reinterpret_cast, as I prefer it to using a million static_casts. – Adam Martin Jul 10 '16 at 19:59

1 Answers1

5

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.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131