简体   繁体   中英

Assign enum member to void pointer?

I have a void pointer that has to hold some information and there I wanted to assign it to a int based on my enumeration. I want this integer to be available through all the time so that the void pointer isn't pointing to "garbage". Here is the code:

enum type {nc, ns, nd};

void* thatType;

thatType = &nc

The outcome of this, is that I get this error: expression must be an lvalue or a function designator So is "nc" an actual variable or does it just work like a placeholder for the integer of 0? If I then did this:

thatType = (int*)nc

First of all, why does this not give me an error then?

Those are two very different things.

&nc

This is trying to take the address of an enumerator, but enumerators aren't objects and don't have addresses. It's like trying to write &42 to get the address of the literal 42 . Only string literals have addresses (more or less).


(int*)nc

This, on the other hand, is taking the integer value of nc (which is 0 ) and converting it to a pointer. Basically you're writing (int*)nullptr . That's legal, though questionable (which is why, of the C++ casts, only a reinterpret_cast will compile here).

Notice in particular that you did not write (int*)&nc .


does it just work like a placeholder for the integer of 0?

Basically, yes, that's right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM