A while ago I was hunting for bug a that was causing wrong numeric data being written to log files. Turned out that the problem was that code equivalent to the following:
int main(void) {
struct {
double a;
int b;
} s = { 1, 2 };
printf("%lf\n", s.a);
printf("%lf\n", s.b);
}
was outputting
1.000000
1.000000
Apparently printf
was expecting the second value in floating point registers, not in the stack. To prevent such mistakes from happening in the future, should one cast all printf parameters to be sure that they really are of the expected type?
According to C99 standard.
Mismatch in format specifier and datatype of actual data to be printed is Undefined behavior
Here b
is and int so if you give "%d"
in second printf()
function.
It will print the correct value otherwise Behavior is Undefined
From c99
7.19.6
9 If a conversion specification is invalid, the behavior is undefined.242) If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined
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