UB17⚓︎
Author: Kai Xu
Definition⚓︎
Demotion of one real floating type to another produces a value outside the range that can be represented (6.3.1.5).
将一个实浮点数向下转化为一个超出表示范围的数
Description⚓︎
For example, the maximum value of floating-point type is 0x7f7f_ ffff (greater than 3.4e^38^), while integer type has a maximum of 0x7fff_ ffff (2147483647), the behavior of converting maximum value of floating-point type to integer type is undefined
例如,float类型最大值为0x7f7f_ffff(大于3.4e38),而integer类型最大为0x7fff_ffff(2147483647),将float_max转化成int的行为是未定义的
Code⚓︎
#include<stdio.h>
#include<float.h>
int main() {
int f_max_2_i = (int) FLT_MAX;
printf("float_max: %f\n", FLT_MAX);
printf("float_max_to_int: %d\n", f_max_2_i);
return 0;
}
Configurations⚓︎
OS: Microsoft Windows 10 22H2
gcc -v: gcc version 8.1.0 x86_64-w64-mingw32
compile and run commands: gcc -o UB17.exe UB17.c && UB17.exe
OS: arm64-apple-darwin20.6.0
clang -v: Apple clang version 13.0.0 (clang-1300.0.29.30)
compile and run commands: clang -o UB17.out UB17.c && ./UB17.out
Behaviors⚓︎
float_max: 340282346638528859811704183484516925440.000000 float_max_to_int: 2147483647
float_max: 340282346638528859811704183484516925440.000000 float_max_to_int: 0
Advice⚓︎
Forced Type conversion is not recommended. If necessary, it needs to use the if statement to determine whether the value is out of bounds
不建议进行强制类型转换;如有必要,需要通过if语句判断值是否越界