Can you please explain the output of this C program? I guess that the problem is with the stack getting corrupt during printf("%d\n",t);
function call because I'm pushing a float
but reading an int
. I'm not sure.
#include <stdio.h>
int main()
{
long x;
float t;
scanf("%f",&t);
printf("%d\n",t);
x=30;
printf("%f\n",x);
{
x=9;
printf("%f\n",x);
{
x=10;
printf("%f\n",x);
}
printf("%f\n",x);
}
x==9;
printf("%f\n",x);
}
And the output
$ ./a.out
20.39
0
20.389999
20.389999
20.389999
20.389999
20.389999
$
What happens is that you lie to the compiler ... first you tell it you are going to send an int
to printf but you send a float instead, and then you tell it you are going to send a double
but you send a long
instead.
Don't do that. Don't lie to the compiler.
You have invoked Undefined Behaviour. Anything can happen. Your program might corrupt the stack; it might output what you expect; it might make lemon juice come out of the USB port; it might make demons fly out of your nose; ...
You are using the wrong format specifier to print long. Use format specifier %ld
instead.
Results
printf("%f\n",x);
// ^ change this to %ld
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With