C++ unions vs. reinterpret_cast -
it appears other stackoverflow questions , reading §9.5.1 of iso/iec draft c++ standard standard use of unions literal reinterpret_cast
of data undefined behavior.
consider code below. goal take integer value of 0xffff
, literally interpret series of bits in ieee 754 floating point. (binary convert shows visually how done.)
#include <iostream> using namespace std; union uniontype { int myint; float myfloat; }; int main() { int = 0xffff; uniontype u; u.myint = i; cout << "size of int " << sizeof(int) << endl; cout << "size of float " << sizeof(float) << endl; cout << "myint " << u.myint << endl; cout << "myfloat " << u.myfloat << endl; float thefloat = *reinterpret_cast<float*>(&i); cout << "thefloat " << thefloat << endl; return 0; }
the output of code, using both gcc , clang compilers expected.
size of int 4 size of float 4 myint 65535 myfloat 9.18341e-41 thefloat 9.18341e-41
my question is, standard preclude value of myfloat
being deterministic? use of reinterpret_cast
better in way perform type of conversion?
the standard states following in §9.5.1:
in union, at 1 of non-static data members can active @ time, is, value of @ 1 of non-static data members can stored in union @ time. [...] size of union sufficient contain largest of non-static data members. each non-static data member allocated if sole member of struct. all non-static data members of union object have same address.
the last sentence, guaranteeing non-static members have same address, seems indicate use of union guaranteed identical use of reinterpret_cast
, earlier statement active data members seems preclude guarantee.
so construct more correct?
edit: using intel's icpc
compiler, above code produces more interesting results:
$ icpc union.cpp $ ./a.out size of int 4 size of float 4 myint 65535 myfloat 0 thefloat 0
the reason it's undefined because there's no guarantee value representations of int
, float
are. c++ standard doesn't float
stored ieee 754 single-precision floating point number. should standard treating int
object value 0xffff
float
? doesn't other fact undefined.
practically, however, purpose of reinterpret_cast
- tell compiler ignore knows types of objects , trust int
float
. it's used machine-specific bit-level jiggery-pokery. c++ standard doesn't guarantee once it. @ point, it's understand compiler , machine in situation.
this true both union
, reinterpret_cast
approaches. suggest reinterpret_cast
"better" task, since makes intent clearer. however, keeping code well-defined best approach.
Comments
Post a Comment