In a class quiz, I was asked to write the output of the below code snippet.
x = 1.234;
printf("x=%2d");
The variable x
contains point values so I assumed it to be a float/double type.
In the paper I answered that this code would just simply print the statement within quotes (as x=%2d
), as in print function it prints whatever within the " " as it is.
But later I ran the code in my compiler to find the output as x=4199232
(The number varied in different compilers though)
(Edit- I added the compiled code here)
#include <stdio.h>
int main() {
float x = 1.234;
printf("x=%2d");
return 0;
}
Can anybody kindly explain me what is really happening here.
The code has undefined behavior (which explains why the number varied in different compilers) because you do not provide an argument of type int
for the conversion %2d
.
If you had written this:
x = 1.234;
printf("x=%2d", x);
The output would depend on the type of x
which does not appear in the code fragment. If x
is defined with type int
or a smaller integer type, including _Bool
, the output should be x= 1
, but if x
has any other arithmetic type, including float
and double
, the behavior is again undefined because the argument does not have the expected type for %d
.
Note also that there is no trailing \n
in the format string, so the output might be delayed until the end of the program and might not appear at all on some non conformant systems.
In your sample code, the behavior is undefined because of the missing argument to printf
, but you do define x
as a float
, which would be implicitly converted as a double
when passed to printf
, invalid for %d
.
Here is a modified version:
#include <stdio.h>
int main() {
double x = 1.234; // only use `float` when necessary
printf("x=%2d\n", (int)x); // outputs `x= 1`
printf("x=%2f\n", x); // outputs `x=1.234000`
printf("x=%2g\n", x); // outputs `x=1.234`
printf("x=%.2f\n", x); // outputs `x=1.23`
return 0;
}