lundi 22 mai 2017

Is it safe to convert a pointer to typed/sized enum to a pointer to the underlying type?

The following code:

enum E : uint8_t { X, Y, Z };
void f(uint8_t* a) {}

int main(void) {
  E e = X;
  f(&e);  // <- error here
}

Produces the following error:

/tmp/c.cc:10:3: error: no matching function for call to 'f'
  f(&e);
  ^
/tmp/c.cc:5:6: note: candidate function not viable: no known conversion from 'E *' to 'uint8_t *' (aka 'unsigned char *') for 1st argument
void f(uint8_t* e) { }

Which is surprising to me because I thought the : uint8_t in the enum's definition would mean they are necessarily represented with that underlying type. I can easily get around this with a cast:

f((uint8_t*)&e);

which I don't mind too much, but given that it's an error to omit it, is this always safe or is the : uint8_t not providing the guarantees I think it is?

Aucun commentaire:

Enregistrer un commentaire