int a=5;
float b=3.5;
printf(\"%d\",b);
printf(\"\\n%f\",a);
Can anyone please tell me why this code is showing unexpected output (garbage\\n3.5)>
Format string incorrect error, according to your declarations of a
and b
:
printf("%d",b); <-- "b is float" Wrong!
printf("\n%f",a); <-- "a is an int" Wrong! -- Undefined behavior
should be:
printf("%f",b);
printf("\n%d",a);
Q :- Why you getting that output?
It's due to undefined behavior of your code:
From INTERNATIONAL STANDARD ©ISO/IEC ISO/IEC 9899:201x
7.16.1 Variable argument list access macros
(page 270)
7.16.1.1 The
va_arg
macro[...] If there is no actual next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the
behavior is undefined
, except for the following cases:
— one type is asigned integer type
, the other type is the correspondingunsigned integer
type, and the value is representable in both types;
— one type is pointer tovoid
and the other is a pointer to a character type