horrible, sneaky ways around cast

Started by
21 comments, last by Sneftel 20 years, 10 months ago
suppose I have this function: void* intToVoidPtr(int i) { /* ... */ return /*...*/; } This function simply casts the given integer to the void pointer address of the same value. Now here''s the caveat: no explicit casts of any kind. You can do whatever else you want, as long as it adheres to the C++ standard and works on "most" architectures. Oh, and before anyone accuses me, this isn''t homework. I''m way beyond learning C++. I just thought of this during my EE discussion, and thought up a couple of solutions, and wanted to see if there are any others I''m not thinking of. How appropriate. You fight like a cow.
Advertisement
That''s a nice fun low level way to get people who don''t know about the stack beating their head into the wall, but what''s the problem with explicit casting?

char* b = 0;
b += i;
return b;
quote:Original post by Cherez
That''s a nice fun low level way to get people who don''t know about the stack beating their head into the wall, but what''s the problem with explicit casting?


Eh, nothing, really. Just a fun exercise that tests your knowledge of the language standard.
Yup. Points for the first solution to civguy and Diodor.

How appropriate. You fight like a cow.
Here''s mine, although I didn''t try it out, just flying by the seat of my pants:


  void* intToVoidPtr(int i) {  union wrapper {    int _i;    void* _ptr;  };  wrapper wrap;  wrap._i = i;  return wrap._ptr;}  


Regards,
Jeff
*claps*

Any others? I just thought one up, but don''t know enough about the underlying operations yet....

How appropriate. You fight like a cow.
Of course my solution will only work on platforms where sizeof(int) == sizeof(void*)...
quote:Original post by rypyr
Of course my solution will only work on platforms where sizeof(int) == sizeof(void*)...

True, but if we''re talking about a direct conversion, then this should be taken as a given. Besides, even if int and void* are of different sizes, your solution will work if the machine is little-endian....

How appropriate. You fight like a cow.
void* intToVoidPtr(int i){   void *p;   memcpy(&p, &i, sizeof(void*));   return p;} 


Assuming a pointer-to-void is the same size as an int, but I get chastized for the pointer-to-int to pointer-to-void conversion, don''t I? How about...

void* intToVoidPtr(int i){   void *p;   stringstream ss(stringstream::in|stringstream::out);   ss << i;   ss >> p;   return p;} 

This topic is closed to new replies.

Advertisement