简体   繁体   English

输出以下代码的原因:

[英]Reason for the output of the following code :

I have a few lines of code for which I could't understand the reason for this output.. 我有几行代码,我无法理解这个输出的原因..

int main()
{
int a=5;
float b=10.5,c=11.0;
printf("%d",b);
printf("\n%d",c);
printf("\n%f",a);
return 0; 
}

O/p in Visual C++ :- 0 ,0 ,0.000000 Visual C ++中的O / p: - 0,0,0.000000

gcc compiler :- 0,0, 11.000000 gcc编译器: - 0,0,1.000000

When you call a variadic function like printf , float s undergo promotion to double . 当你调用像printf这样的可变函数时, float s会升级为double int s are passed as-is. int按原样传递。 printf therefore expects a double when you write %f , and an int when you write %d . 因此, printf在写入%f时需要一个double ,在写入%d时需要一个int

Not giving it a double , but an int , is therefore undefined behaviour . 因此,不给它一个double ,而是一个int ,是未定义的行为 Similarly, passing a double when the function expects an int is also undefined. 类似地,当函数期望int时传递double也是未定义的。

As usual, undefined behaviour means "anything could happen". 像往常一样,未定义的行为意味着“任何事都可能发生”。 Never, ever rely on undefined behaviour. 永远不要依赖未定义的行为。

You are playing with undefined or unspecified behavior. 您正在玩未定义或未指定的行为。 Not sure which one of them it is. 不确定它们是哪一个。 On my Debian with gcc 4.7.2, I get -780714744, 4195886, 11.000000 on the output. 在我使用gcc 4.7.2的Debian上,输出中得到-780714744,4199588,11.000000。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM