-3
#include<stdio.h>
#include<conio.h>
void main()
{
printf("%%%%%");
}

The output of the above program is %%% ,how come?

D77pak
  • 21
  • 3

3 Answers3

1

This is simply, because the standard says:

4 Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

[...]

8 The conversion specifiers and their meanings are:

[...]

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

(From ISO/IEC 9899:TC3 -> §7.19.6.1 Library)

dhein
  • 6,431
  • 4
  • 42
  • 74
  • can you please elaborate!! – D77pak Dec 02 '13 at 13:43
  • @user2873941 well this is the c99 standard, and it says, the `%` operator is introducing a placeholder which is specified by the followed characters. in the pointed phrase there are all signs listed and this is the section what a `%` does as palceholder. – dhein Dec 02 '13 at 13:45
  • ok but when i try printf("% %s")...output is % %s..how? – D77pak Dec 02 '13 at 13:47
  • @user2873941 Because there is a space? `space — If the first character of a signed conversion is not a sign, or if a signed conversion results in no characters, a space is prefixed to the result. If the space and + flags both appear, the space flag is ignored.` (Quote from same section of c99 standard abotu what a space preceded by a `%` operators behaving is. – dhein Dec 02 '13 at 13:49
1

You have unspecified behaviour. You have 5 %s in that format string. A % is followed by a format character, which controls what printf does with its arguments. So the 1st % is followed by another %, which printf outputs as a %. Similarly the 3rd and 4th %s.

However, the 5th % is followed by a null byte. And to quote the man page for printf:

If a character sequence in the format operand begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified.

So it could print %, print nothing, crash, ...

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
  • Your correct. but you should add to your quite that this behaving is just implementation depending. – dhein Dec 02 '13 at 14:31
  • it is unspecified. not implementation dependant. If it was implementation dependant, the implementation would need to define how it behaved. This is unspecified, and could behave differently tomorrow.It could behave differently in the same program. – Tom Tanner Dec 02 '13 at 14:41
0

It depends on the compiler/platform... The fact you are using <conio.h> tells me you are on DOS/Windows platform.

on the Linux side I get simply "%%" as output.

PS: please see What are the different valid prototypes of 'main' function?

Community
  • 1
  • 1
Giupo
  • 413
  • 2
  • 9