用浮点格式说明符打印整型变量 [英] Printing int variables with float format specifier
问题描述
int main()
{
int a = 5;
float b = 7.5;
printf(%d%f \ n,a,b);
printf(%d%f \ n,a,a);
返回0;
}
当我在gcc编译器中编译输出结果是
5 7.500000
5 7.500000
但是在visual studio中,输出是
5 7.500000
5 0.000000
code>
我无法理解gcc编译器的输出。
int printf(const char *格式,...);
C11(n1570),§6.5.2.2函数调用
函数原型声明器中的省略号表示法导致
参数类型转换在上次声明的参数后停止。 默认参数
的促销活动是在结尾参数上执行的。
C11(n1570) 6.5.2.2函数调用
对每个参数执行整数提升,将
的类型为float的参数提升为double 。这些被称为默认参数
promotions。
对每个参数执行整数提升,将
的类型为float的参数提升为double 。这些被称为默认参数
promotions。
因此,没有其他的参数提升用 printf
调用。特别是, a
不会转换为 double
。因此,它会导致一个未定义的行为: printf
会尝试获得给定大小的 double
( sizeof(double)
)和一个给定的内存表示,它可能不同于 int
。
C11(n1570),§7.21.6.1 fprintf
函数
如果转换规范无效,则行为是未定义的。如果任何参数不是相应转换规范的正确类型,则行为是未定义的。
另外,您可以查看ASM由 gcc 生成的代码来查看发生了什么。
int main()
{
int a=5;
float b=7.5;
printf("%d %f\n",a,b);
printf("%d %f\n",a,a);
return 0;
}
when i compile this in gcc compiler output is
5 7.500000
5 7.500000
But when in visual studio, output is
5 7.500000
5 0.000000
I am not able to understand gcc compiler output.
printf
prototype is:
int printf(const char *format, ...);
C11 (n1570), § 6.5.2.2 Function calls
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 Function calls
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.
Therefore, no other argument promotion is performed with a printf
call. In particular, a
is not converted to double
. Hence it will result in a undefined behavior: printf
will try to get a double
with a given size (sizeof(double)
) and a given memory representation, which could be different from an int
.
C11 (n1570), § 7.21.6.1 The fprintf
function
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.
Besides, you can look at the ASM code generated by gcc to see what is going on.
这篇关于用浮点格式说明符打印整型变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!