Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting an enum through a void *

I'm trying to convert some old 32 bit code to 64 bit. One of the more frequent warnings I get is:

warning: cast of pointer to integer of different size

this happens when a function calls pthread_create which accepts a void * for passing data to the new thread. The calling thread puts in that void * an enum (hence the size mismatch in 64bit). Here's the code:

typedef enum {
zero,
one,
two
}numbers_e;

some_function(...)
{
    numbers_e mydata=zero;

    ...
    pthread_create(..., (void *)mydata);
    ...
}

I managed to overcome the warning with this:

pthread_create(..., (void *)0 + my_data);

this solution is very ugly (and I'm pondering if it's better to leave the warning as is with a big remark near the code using it). Is there another solution ?

like image 306
Dror Cohen Avatar asked Sep 02 '26 15:09

Dror Cohen


1 Answers

your solution is not only ugly, it is undefined behaviour (UB) that could cause you problems in the future:

  • arithmetic on void* pointers is non standard and must be an extension of your compiler
  • arithmetic on pointer that don't point to valid object is UB

To avoid the first you could use (char*)0 + my_data, but this would still leave you with the second.

What you could do

  • cast your value to uintptr_t. this is a type that is guaranteed to be compatible with void*, if it exists. It exists on most modern platforms. The advatage would be that your code wouldn't compile on platforms where it doesn't exist, a clear indication that you'd have to change something, then.
  • use a pointer to the data. this is the real solution, the way pthreads are designed

For both you'd have to modify the source of the called function, though, so you'd well change it to the second, the way how this should be.

like image 65
Jens Gustedt Avatar answered Sep 05 '26 16:09

Jens Gustedt