简体   繁体   中英

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

gcc compiler :- 0,0, 11.000000

When you call a variadic function like printf , float s undergo promotion to double . int s are passed as-is. printf therefore expects a double when you write %f , and an int when you write %d .

Not giving it a double , but an int , is therefore undefined behaviour . Similarly, passing a double when the function expects an int is also undefined.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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