C99和C11中的有效类型规则规定,没有声明类型的存储可以用任何类型写入,并且存储非字符类型的值将相应地设置存储的有效类型。
抛开 INT_MAX 可能小于 123456789 的事实不谈,以下代码对有效类型规则的使用是否严格符合?
#include <stdlib.h>
#include <stdio.h>
/* Performs some calculations using using int, then float,
then int.
If both results are desired, do_test(intbuff, floatbuff, 1);
For int only, do_test(intbuff, intbuff, 1);
For float only, do_test(floatbuff, float_buff, 0);
The latter two usages require storage with no declared type.
*/
void do_test(void *p1, void *p2, int leave_as_int)
{
*(int*)p1 = 1234000000;
float f = *(int*)p1;
*(float*)p2 = f*2-1234000000.0f;
if (leave_as_int)
{
int i = *(float*)p2;
*(int*)p1 = i+567890;
}
}
void (*volatile test)(void *p1, void *p2, int leave_as_int) = do_test;
int main(void)
{
int iresult;
float fresult;
void *p = malloc(sizeof(int) + sizeof(float));
if (p)
{
test(p,p,1);
iresult = *(int*)p;
test(p,p,0);
fresult = *(float*)p;
free(p);
printf("%10d %15.2f\n", iresult,fresult);
}
return 0;
}
根据我对标准的阅读,注释中描述的函数的所有三种用法都应该严格符合(整数范围问题除外)。因此代码应该输出1234567890 1234000000.00
。然而,GCC 7.2 输出1234056789 1157904.00
。我认为当leave_as_int
为 0,则存储 123400000*p1
将 123400000.0f 存储到*p2
,但我在标准中没有看到任何授权这种行为的内容。我错过了什么,还是 gcc 不符合要求?