Reputation: 575
In C, on mentioning three backslashes, like so:
#include <stdio.h>
int main() {
printf(" \\\ ");
}
prints out just one backslash in the output. Why and how does this work?
Upvotes: 1
Views: 1475
Reputation: 5591
It is indeed a very simple operation in c
. A \
is just a escape sequences. Hence below statement will print two slash.
printf(" \\\\ ");
For example some characters in c
are represented with a slash like end of a line character \n
or end of a string character \0
etc. But if you want to print such a character as it is what will you do? Hence you need to add a escape sequence character in front of it:
printf("\\n"); // will print \n
But
printf("\n"); // will print end of character hence you don't see anything in output
Upvotes: 1
Reputation: 34638
C11; 6.4.4.4 Character constants:
The double-quote
"
and question-mark?
are representable either by themselves or by the escape sequences\"
and\?
, respectively, but the single-quote'
and the backslash\
shall be represented, respectively, by the escape sequences\'
and\\
.
So, To represent a single backslash, it’s necessary to place double backslashes \\
in the source code. To print two \\
you need four backslash \\\\
. In your code extra \
is a space character, which isn't valid.
Upvotes: 1
Reputation: 399959
That sequence is:
The C11 draft says (in note 77):
The semantics of these characters were discussed in 5.2.2. If any other character follows a backslash, the result is not a token and a diagnostic is required.
On godbolt.org I got:
<source>:8:14: warning: unknown escape sequence '\ ' [-Wunknown-escape-sequence]
So you seem to be using a non-conforming compiler, which chooses to implement undefined backslash sequences by just letting the character through.
Upvotes: 5
Reputation: 11889
That is printing:
space
slash
escaped space
The 3rd slash is being interpreted as "slash space"
Upvotes: 1