views:

88

answers:

4

What is the output of the following and what's the reason behind this?

main()
{
    printf("%%%%");
}

The answer is "%%", but I don't know why.

+8  A: 

% is the beginning of a format-specifier. (For example, "%d" means "print an int".) A % after the format-specifier escapes it, printing a single "%".

That is, in the same way "\\" results in a single backslash, "%%" results in a single percent-sign.

GMan
+1  A: 

in printf, % is usually used to indicate a token such as %s or %d or %5.2f. If you want to output a literal %, you use %%.

Jamie Wong
+3  A: 

Technically, the output could be anything since you didn't print a newline at the end, and also because you didn't include stdio.h :-).

However, correcting the two mistakes:

#include <stdio.h>

int main(void)
{
    printf("%%%%\n");
    return 0;
}

The above should print %% followed by a newline.

Each conversion specification is introduced by the character %.

...

The conversion specifiers and their meanings are:

...

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

(C99 7.19.6.1).

Alok
+1 for the quote.
GMan
The lack of a newline does not make the output undefined.
Michael Speer
@Michael: http://groups.google.com/group/comp.lang.c/browse_thread/thread/56f1d712aa8ffd31 (or see 7.19.2p2 in C99).
Alok
The C standard allows a lot of idiotic things in file behavior, like random extra 0 bytes appearing at the end of binary files and fixed-size, line-record-based text files. There's a big difference in the standard allowing idiotic things to avoid making ancient legacy systems that can't be fixed non-conformant, and allowing useful diversity to avoid keeping us stuck in the present implementation. On any real present-day system with byte-stream files (one special case is those where binary and text modes are equivalent and documented as such), missing final newline has no ill consequences.
R..
A: 
Format specifiers are typically introduced by a % character,
and a literal percent sign can be copied into the output 
using the escape sequence %%.

Source.

Thus you can print % in the output using %%. The question has a series of % symbols, hence the output is %%.

Praveen S