-2

I ran the following code segment in C:

    printf("%%%\n");

I got the output "%" (without quotes). Can anyone explain what exactly happened? Why we got only one % sign in result?

1 Answers1

4

%% will print %. %\n is not a valid conversion specifier.

You should always enable warnings. See the following:

 warning: unknown conversion type character 0xa in format [-Wformat=]
     printf("%\n");
                 ^

As noted in the comments, this is undefined behavior because according to the C11 standard, it is undefined behavior if:

— An invalid conversion specification is found in the format for one of the formatted input/ouptut functions [...]

  • why I got two `%%` as output? – rakib_ Sep 25 '14 at 09:25
  • @rakib Because %\n is not a valid format specifier. Because You should always enable warnings. – Pascal Cuoq Sep 25 '14 at 09:27
  • I ran the code on Codeblocks13.12 using GNU GCC Compiler, & It gave only one % sign with no warnings.. I even ran the printf("%\n"); but it also did not give any warnings.. I think warnings are enabled in my computer (coz I got some warnings in different questions).. Can you explain why is this happening? – Prakhar Awasthi Sep 25 '14 at 09:28
  • @PascalCuoq ya, but that does explain why it shows `%%` output. – rakib_ Sep 25 '14 at 09:29
  • @Prakhar I picked the wrong standard quote. See edit. –  Sep 25 '14 at 09:35