Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I cast int and BOOL to void*, but not float?

Tags:

c++

c

objective-c

void* is a useful feature of C and derivative languages. For example, it's possible to use void* to store objective-C object pointers in a C++ class.

I was working on a type conversion framework recently and due to time constraints was a little lazy - so I used void*... That's how this question came up:

Why can I typecast int to void*, but not float to void* ?

like image 893
Jasper Blues Avatar asked Jan 11 '13 06:01

Jasper Blues


1 Answers

BOOL is not a C++ type. It's probably typedef or defined somewhere, and in these cases, it would be the same as int. Windows, for example, has this in Windef.h:

    typedef int                 BOOL;

so your question reduces to, why can you typecast int to void*, but not float to void*?

int to void* is ok but generally not recommended (and some compilers will warn about it) because they are inherently the same in representation. A pointer is basically an integer that points to an address in memory.

float to void* is not ok because the interpretation of the float value and the actual bits representing it are different. For example, if you do:

   float x = 1.0;

what it does is it sets the 32 bit memory to 00 00 80 3f (the actual representation of the float value 1.0 in IEEE single precision). When you cast a float to a void*, the interpretation is ambiguous. Do you mean the pointer that points to location 1 in memory? or do you mean the pointer that points to location 3f800000 (assuming little endian) in memory?

Of course, if you are sure which of the two cases you want, there is always a way to get around the problem. For example:

  void* u = (void*)((int)x);        // first case
  void* u = (void*)(((unsigned short*)(&x))[0] | (((unsigned int)((unsigned short*)(&x))[1]) << 16)); // second case
like image 185
thang Avatar answered Sep 26 '22 03:09

thang