+ 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)

17th Jul 2021, 10:32 AM
abhinav
abhinav - avatar
5 Respostas
+ 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.
17th Jul 2021, 10:52 AM
Ipang
+ 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.
17th Jul 2021, 10:57 AM
abhinav
abhinav - avatar
+ 2
Yes Abhinav, I tested your snippet in C4Droid and also Code Playground, and also get different outputs 👌
17th Jul 2021, 10:59 AM
Ipang
+ 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?
10th Aug 2021, 5:21 PM
Calvin Thomas
Calvin Thomas - avatar