+ 1
Unexpected Output
Why does this outputs 3? int a = 3; float b = 5.89f; printf("%d", b); The output is always the value of the latest defined int variable (here 'a') and remains unchanged: - After interchanging the positions of the definitions. - Also if datatype of b is double. - If b is uninitialized. - If there's simply printf("%d", 24.8)
5 Réponses
+ 5
"The output is always the value of the latest int variable ..."
Actually not, it outputs varying value on each run, not value of <a>.
Use of inappropriate format specifier leads to undefined behaviour (unexpected output).
In Code Playground you will see a warning about wrong format specifier.
+ 3
Thanks Ipang. I was running it on a different platform (Cxxdroid). So it can be concluded that this undefined behaviour is specific to platform.
+ 2
Yes Abhinav,
I tested your snippet in C4Droid and also Code Playground, and also get different outputs 👌
+ 1
Ipang But anyway, the float format specifier reads 4 bytes from the integer data block, which is obviously not in the same format. So what makes the output unpredictable?