请测试以下代码:
#include <stdio.h>
#include <stdlib.h>
main()
{
const char *yytext="0";
const float f=(float)atof(yytext);
size_t t = *((size_t*)&f);
printf("t should be 0 but is %d\n", t);
}
使用以下命令进行编译:
gcc -O3 test.c
良好的输出应该是:
"t should be 0 but is 0"
然而,我的gcc 4.1.3版本却出现了以下问题:
"t should be 0 but is -1209357172"
%d
格式说明符打印size_t
表达式是UB。您需要%zu
,否则需要将其转换为int
。此外,size_t
可能比float
大(例如,在64位机器上),因此您应该使用uint32_t
,它始终与IEEE 754兼容实现中的float
大小相同。 - R.. GitHub STOP HELPING ICE