TITLE: reinterpret_cast<> and type_punning (Newsgroups: comp.std.c++, 27 Jan 97) KANZE: James Kanze |> >>Also, for those not familiar with the term, type punning means telling |> >>the compiler to access the actual bits as if they were a T, regardless |> >>of what it thinks they are. STELDAL: d96-mst@nada.kth.se (Mikael Steldal) |> >It that what reinterpret_cast does? CLAMAGE: stephen.clamage@Eng.Sun.COM (Steve Clamage) |> Here's a quote from the draft standard: |> |> "The mapping performed by reinterpret_cast is implementation-defined. |> [Note: it might, or might not, produce a representation different from |> the original value. ]" |> |> In other words, the result of a reinterpret_cast might or might not |> change the bits, and usage is not portable. |> |> In addition, reinterpret_cast is allowed only for specified kinds of |> conversion. It is not a general type-punning mechanism. (C++ doesn't |> have a general type-punning mechanism.) KANZE: I believe, however, that the intent of the standard is that a reinterpret_cast on a pointer will result in a pointer to the same actual memory location, in so far as possible. (If the cast is to void* or char*, it should always be possible.) In this case, the reinterpret_cast may be used FOR type punning. It doesn't do the punning itself, but provides a mechanism by which the programmer can do it. For example, to look at the underlying representation of a double: double d ; unsigned char* p = reinterpret_cast< unsigned char* >( &d ) ; Dereferencing p is an example of what I would call type punning; obtaining the correct initialization of p is only possible with reinterpret_cast (or an old-style cast which works like a reinterpret_cast). Such type punning is definitly bad programming practice in general. There are exceptions, though; I'd use something like this to implement the library routines frexp and ldexp, for example, and I've used it in the past to hack together an initial guess for a sqrt routine. I also use it for implementing a stack walk-back. And of course, for curiosity's sake, to see what the underlying representation looked like. Of course, all of these uses except the last are extremely implementation dependant. (Even given 8 bit bytes, 16 bit shorts, 64 bit doubles, IEEE format and linear addressing, the floating point routines still need an #if on the byte ordering. And that's a lot of givens to begin with.)