printf
cannot infer the type of the arguments passed to it. The argument will be interpreted as per the corresponding conversion specifier in the format string. Therefore, the arguments must correspond properly to their respective conversion specifiers. Quoting C11 standard § 7.21.6.1 ¶9 about fprintf
If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding
conversion specification, the behavior is undefined.
Again quoting from the C11 standard § 7.21.6.2 ¶13 about fscanf
If a conversion specification is invalid, the behavior is undefined.
Therefore, the following call to scanf
invokes undefined behaviour because u.i
is of type int
but %lf
conversion specifier means you are reading a double
.
scanf("%lf", &u.i);
Please read these -
- What happens when I use the wrong format specifier?
- Wrong format specifiers in scanf or printf
Also, it's undefined behaviour to access the field of a union which was not most recently written.
union {
int i;
double f;
} u;
// undefined behaviour. u.i is of type int but %lf
// means scanf will read a double
scanf("%lf", &u.i);
// undefined behaviour because reading the field u.f
// but the last written field is u.i
printf("%lf", u.f);