Question about reinterpret_cast usage

Hello. I recently was wanting to std::cout a hex
value to the console but it kept evaluating the hex
to decimal (Understandable). So, I remembered
not knowing what reinterpret_cast did, so I wrote
up this code:

1
2
3
4
5
6
7
#include <iostream>

int main()
{
    //std::cout << 0xFF <-- prints 255
    std::cout << reinterpret_cast<int*>(0xFF); // prints 0xFF
}


the uncommented line does what I wanted. So, my question,
is using reinterpret_cast in this way good practice? Is
it the exact intended action of reinterpret_cast? (I doubt it)
Last edited on
If you want hex, do this
 
std::cout << std::hex << std::showbase << 0xFF << std::endl;


> So, my question, is using reinterpret_cast in this way good practice?
No.

> Is it the exact intended action of reinterpret_cast?
You get an architecture dependent representation of a pointer, which may not be the same as what you want. Ultimately, you end up with whatever the "%p" conversion of printf would give you, and that basically says "The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an implementation-defined
manner.".
Topic archived. No new replies allowed.