Date: 2015jun18
Update: 2026sep23
Language: C/C++
Q. C/C++: Cast a void * into an enum. Such as at the start of a thread.
A. Cast to intptr_t first, like this:
void *threadMain(void *in) {
MyEnum myenum = (MyEnum) (intptr_t) in;
...
return NULL;
}
Full Example:
#include <stdio.h>
#include <unistd.h> // for sleep()
#include <cstdint> // for intptr_t
#include <pthread.h>
enum Fruit { Apple, Banana, Cherry };
void *threadMain(void *in) {
Fruit fruit = (Fruit) (intptr_t) in; // HERE IS THE DOUBLE UN-CAST
printf("%s: fruit=%d\n", __FUNCTION__, fruit);
pthread_exit(NULL);
return NULL;
}
int main(int argc, char *argv[]) {
Fruit fruit = Cherry;
pthread_t threadHandle;
// THE OPPOSITE CAST
pthread_create(&threadHandle, NULL, threadMain, (void *)(intptr_t)fruit);
sleep(10); // Delay ending the program
}
Output:
threadMain: fruit=2