int main()
{
int a=5;
float b=7.5;
printf("%d %f\n",a,b);
printf("%d %f\n",a,a);
return 0;
}
当我在 gcc 编译器中编译时输出是
5 7.500000
5 7.500000
但是在visual studio中,输出是
5 7.500000
5 0.000000
我无法理解 gcc 编译器的输出。
最佳答案
printf
原型(prototype)是:
int printf(const char *format, ...);
C11 (n1570),§ 6.5.2.2 函数调用
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
C11 (n1570),§ 6.5.2.2 函数调用
the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.
因此,printf
调用不会执行其他参数提升。特别是,a
不会转换为 double
。因此,它将导致未定义的行为:printf
将尝试获取具有给定大小 (sizeof(double)
) 和给定值的 double
内存表示,可能与 int
不同。
C11 (n1570),§ 7.21.6.1 fprintf
函数
If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
此外,您可以查看gcc 生成的ASM 代码以了解发生了什么。
关于c - 使用 float 格式说明符打印 int 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17104102/