the following code is not showing the expected output which is garbage value ( strangely the values are swapped )
#include<stdio.h>
int main()
{
float f = 4.6;
int d = 7;
printf("%d %f\n",f,d);
return 0;
}
output: 7 4.600000
Let's reduce this a bit:
float f = 4.6;
printf("%d\n", f);
That's undefined behavior. The correct format specifier must be given an argument of the correct type.
Undefined behavior can cause any outcome, including this odd outcome that you are seeing.
Now, you might be asking why a compiler would even produce this code. So let's look at the x86-64 assembly for 2 codes:
int main() {
float f = 4.6;
int d = 7;
printf("%d %f\n", d, f);
return 0;
}
int main() {
float f = 4.6;
int d = 7;
printf("%f %d\n", f, d);
return 0;
}
Other than the format string, these two codes produce identical assembly. This is likely because the calling convention requires floats to be placed in different registers than integers, or that floats should be passed on the stack (or any number of other rules that handle floats and integers differently).
This should make it clearer why the code you posted is still producing something useful, even though the code is just broken.
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