Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do '?' and '\?' give the same output in C?

Tags:

c

escaping

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 '?'?

like image 824
Krish Avatar asked May 17 '18 09:05

Krish


3 Answers

\? is an escape sequence exactly equivalent to ?, and is used to escape trigraphs:

#include <stdio.h>
int main(void) {
    printf("%s %s", "??=", "?\?="); // output is # ??=
}
like image 147
Bathsheba Avatar answered Oct 21 '22 20:10

Bathsheba


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 ?.

like image 28
Ajay Brahmakshatriya Avatar answered Oct 21 '22 21:10

Ajay Brahmakshatriya


Because '\?' is a valid escape code, and is equal to a question-mark.

like image 20
Some programmer dude Avatar answered Oct 21 '22 19:10

Some programmer dude