Reputation: 622
Why one single \
in a printf
function does not show in the output console screen but double \\
does?
#include <stdio.h>
#include <stdlib.h>
int main()
{
//why is double \\ necessary?
printf("\\");
printf("\");
//why here shown error in the second printf?
printf(" " "dd " " ");
//why its executed successfully
printf(" " "" ");
//why it is shown errow
return 0;
}
Upvotes: 3
Views: 462
Reputation: 94
backslash is used for Escape sequences.
An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly. (From wikipedia)
In C , look :
\n for new line , \t for tab are used. here back slash is used as an escape sequence which doesnot represent itself
printf("\\");
here , first backslash is used as escape sequence. so second \ backslash will be printed. but
printf("\");
but for this case , only escape sequence . so it will show a error
Upvotes: 2
Reputation: 4023
The \
in the printf()
statement is used for escaping characters. For example, \n
means newline
, \0
means null character
. etc. Therefore, when you use simply a \
, it expects some character which is to be escaped. In the second printf()
, the character to be escaped becomes "
, rendering your printf()
statement incomplete. So it shows an error, whereas in the first code, there is a \
after the first \
, so it is treated as a character to be displayed rather than an escape character.
From Wikipedia
An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.
Upvotes: 4
Reputation: 21
because back slash i.e. \ is used for escape sequences. These escape sequences are used for performing special tasks like formatting, playing a beep (\a) and since it is treated as a special character the compiler thinks that you want to perform some special task when you write "\" in printf which means you won't be able to print \ so in order to print \ you just type it twice "\"
Upvotes: 2
Reputation: 145839
\
is already used as the first character for escape sequences, for example \n
is the new line and \t
is the horizontal tab. To print a \
character you need the \\
escape sequence.
Upvotes: 3