Why cast to a pointer then dereference?

后端 未结 5 983
心在旅途
心在旅途 2020-12-18 19:06

I was going through this example which has a function outputting a hex bit pattern to represent an arbitrary float.

void ExamineFloat(float fValue)
{
    pr         


        
5条回答
  •  无人及你
    2020-12-18 19:29

    Floating-point values have memory representations: for example the bytes can represent a floating-point value using IEEE 754.

    The first expression *(unsigned long *)&fValue will interpret these bytes as if it was the representation of an unsigned long value. In fact in C standard it results in an undefined behavior (according to the so-called "strict aliasing rule"). In practice, there are issues such as endianness that have to be taken into account.

    The second expression (unsigned long)fValue is C standard compliant. It has a precise meaning:

    C11 (n1570), § 6.3.1.4 Real floating and integer

    When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

提交回复
热议问题