iphone: floats cast to unsigned ints get set to 0 if they are negative?

前端 未结 4 936
余生分开走
余生分开走 2021-01-12 02:45

try it out:

volatile float bob = -344.0f;
unsigned int fred = (unsigned int)bob;

printf(\"%d\\n\",fred);

output will be 0.

obvious

4条回答
  •  忘掉有多难
    2021-01-12 03:12

    §6.3.1.4 of the C standard:

    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.

    So like Paul R said, this is undefined behavior.

提交回复
热议问题