Why do '?' and '\?' give the same output in C?
In C, why do these two pieces of code give the same output?
#include<stdio.h>
int main(void)
{
const char c='\?';
printf("%c",c);
}
and
#include<stdio.h>
int main(void)
{
const char c='?';
printf("%c",c);
}
I understand that a backslash is used to make quotes ("
or '
) and a backslash obvious to the compiler when we use printf(), but why does this work for the '?'?
\?
is an escape sequence exactly equivalent to ?
, and is used to escape trigraphs:
#include <stdio.h>
int main(void) {
printf("%s %s", "??=", "?\?="); // output is # ??=
}
Quoting C11
, chapter §6.4.4.4p4
The double-quote
"
and question-mark?
are representable either by themselves or by the escape sequences\"
and\?
, respectively, but...
.
Emphasis mine
So the escape sequence \?
is treated the same as ?
.
Because '\?'
is a valid escape code, and is equal to a question-mark.