Problems casting NAN floats to int

后端 未结 3 1981
不思量自难忘°
不思量自难忘° 2021-01-17 08:30

Ignoring why I would want to do this, the 754 IEEE fp standard doesn\'t define the behavior for the following:

float h = NAN;
printf(\"%x %d\\n\", (int)h, (         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-17 09:21

    The result of a cast of a floating point number to an integer is undefined/unspecified for values not in the range of the integer variable (±1 for truncation).

    Clause 6.3.1.4:

    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.

    If the implementation defines __STDC_IEC_559__, then for conversions from a floating-point type to an integer type other than _BOOL:

    if the floating value is infinite or NaN or if the integral part of the floating value exceeds the range of the integer type, then the "invalid" floating- point exception is raised and the resulting value is unspecified.

    (Annex F [normative], point 4.)

    If the implementation doesn't define __STDC_IEC_559__, then all bets are off.

提交回复
热议问题