When I run this following code:
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf("%%");
getch();
}
I get % as an output?
What might be the reason behind this logic?
When I run this following code:
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf("%%");
getch();
}
I get % as an output?
What might be the reason behind this logic?
That is what printf
does: it is print formatted (f for formatted). It uses %
as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e. %%
. See the manual for more information on formatting: printf.
P.S.: Never use a string that is not a part of the program as the first argument. To print a string message that was input by a user, do printf(%s, message);
. Otherwise you will have a security hole in your code.
%
comes into format specifiers.
When we write printf("%d", 20);
, it will print 20 rather than %d
. because the compiler treats %
as a format specifier. In the mind of the compiler, the meaning of % is somewhat special.
So if you want that "%" should be the output, then you must write printf("%%")
. Here the first % sign will suppress the meaning of the %
format specifier and will print %
as an output.
From the standard ISO/IEC 9899:1999 (E)
7.19.6.1
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 %%.
For C printf, %
is a special character which typically indicates a parameter to substitute at that position: printf("Hello, %s\n", "World!");
results in "Hello, World!". There are lots of different things you can put after the % depending on the data you want to output. So that leaves the problem of "What if I want to print a percent symbol"?
The solution: Use %%
.
The same is true of the special escape character \
. "\n" means to print a new line. If you want to actually print the forward slash, you have to put it twice \\
See Printf format string and MSDN.