简体   繁体   中英

Printing with format specifiers in C

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;
}

In this statement

printf("x=%2d");

you forgot to specify an argument for the conversion specifier d . So the program will try to output whatever is stored in the memory where the second argument should be.

So the program has undefined behavior.

It will also have undefined behavior if you will specify the second argument like

printf("x=%2d", x );

because there is used an invalid conversion specifier with an object of the type float.

To output just the format string you should write

printf("x=%%2d");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM