Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain the output printf("%0 %x",a);?

Tags:

c

This code is making me so confused. I can't understand what %0 is doing inside printf!

Code:

#include <stdio.h>

int main() {
    int a = 100;
    printf("%0 %x", a);
    return 0;
}

Output

%x
like image 741
S.B Avatar asked Aug 25 '21 16:08

S.B


1 Answers

%0 %x has an invalid printf conversion specification:

  • the 0 is a flag specifying that the number representation should be padded with initial zeroes to the specified width (which is not specified here)

  • the is a flag specifying that the signed conversion should be prefixed with a space if positive in the same place as a - for negative numbers.

  • the second % is the conversion specifier, so the initial part is just a variation of %% with 2 extra flags and thus should cause a % character to be output, but the C Standard specifies in 7.21.6.20 the fprintf function that

    %: A % character is written. No argument is converted. The complete conversion specification shall be %%.

    Hence %0 % is an invalid conversion specification as % does not accept flags.

Most libraries will just output %x, ie: % for %0 % and x for the trailing x, ignoring the a argument, and this is what you get on your system, but the behavior is actually undefined, so nothing can be assumed.

Conversely, printf("|%0 5d|", 100); will output | 0100| but the space is ignored for the x conversion which is unsigned so printf("|%0 5x|", 100); will output |00064|.

like image 128
chqrlie Avatar answered Oct 20 '22 22:10

chqrlie