As others have already noted, casting a pointer to a non-char type to a pointer to a different non-char type and then dereferencing is undefined behavior.
That printf("%08lx\n", *(unsigned long *)&fValue)
invokes undefined behavior does not necessarily mean that running a program that attempts to perform such a travesty will result in hard drive erasure or make nasal demons erupt from ones nose (the two hallmarks of undefined behavior). On a computer in which sizeof(unsigned long)==sizeof(float)
and on which both types have the same alignment requirements, that printf
will almost certainly do what one expects it to do, which is to print the hex representation of the floating point value in question.
This shouldn't be surprising. The C standard openly invites implementations to extend the language. Many of these extensions are in areas that are, strictly speaking, undefined behavior. For example, the POSIX function dlsym returns a void*
, but this function is typically used to find the address of a function rather than a global variable. This means the void pointer returned by dlsym
needs to be cast to a function pointer and then dereferenced to call the function. This is obviously undefined behavior, but it nonetheless works on any POSIX compliant platform. This will not work on a Harvard architecture machine on which pointers to functions have different sizes than do pointers to data.
Similarly, casting a pointer to a float
to a pointer to an unsigned integer and then dereferencing happens to work on almost any computer with almost any compiler in which the size and alignment requirements of that unsigned integer are the same as that of a float
.
That said, using unsigned long
might well get you into trouble. On my computer, an unsigned long
is 64 bits long and has 64 bit alignment requirements. This is not compatible with a float. It would be better to use uint32_t
-- on my computer, that is.
The union hack is one way around this mess:
typedef struct {
float fval;
uint32_t ival;
} float_uint32_t;
Assigning to a float_uint32_t.fval
and accessing from a ``float_uint32_t.ival` used to be undefined behavior. That is no longer the case in C. No compiler that I know of blows nasal demons for the union hack. This was not UB in C++. It was illegal. Until C++11, a compliant C++ compiler had to complain to be compliant.
Any even better way around this mess is to use the %a
format, which has been part of the C standard since 1999:
printf ("%a\n", fValue);
This is simple, easy, portable, and there is no chance of undefined behavior. This prints the hexadecimal/binary representation of the double precision floating point value in question. Since printf
is an archaic function, all float
arguments are converted to double
prior to the call to printf
. This conversion must be exact per the 1999 version of the C standard. One can pick up that exact value via a call to scanf
or its sisters.