I was looking at the escape sequences for characters in strings in c++ and I noticed there is an escape sequence for a question mark. Can someone tell me why this is? It just seems a little odd and I can't figure out what ? does in a string. Thanks.
Asked
Active
Viewed 4,293 times
1 Answers
27
It's to keep a question mark from getting misinterpreted as part of a trigraph.
For example, in
"What??!"
The "??! would be interpreted as the |
character. So, you have to escape the question marks as follows:
"What\?\?!"
Example complements of http://msdn.microsoft.com/en-us/library/bt0y4awe%28VS.80%29.aspx

James McNellis
- 348,265
- 75
- 913
- 977
-
3By default, gcc disables the interpretation of trigraphs, unless they're explicitly enabled with `-trigraphs`, `-ansi`, or some of the `-std=xxx` options. `-Wtrigraphs` (enabled by `-Wall`) also enables warnings for trigraph sequences. – Adam Rosenfield Oct 19 '09 at 03:50
-
2All about trigraphs: http://stackoverflow.com/questions/1234582/purpose-of-trigraph-sequences-in-c/1234618#1234618 – Michael Burr Oct 19 '09 at 05:36
-
2You just ignore the existence of trigraphs... until they bite you in the ass. – Matthieu M. Oct 19 '09 at 15:28
-
@Mattihieu - that's pretty much what I do and it's really not a problem. The tradeoff of once every 7 or 8 years relearning why I hate trigraphs is an acceptable cost to not worrying about them at any other time. But, GCC is right to disable them by default (I think). – Michael Burr Oct 19 '09 at 22:29
-
1An alternate way of writing the indicated string would be `"What?""?!"` (since the compiler will concatenate the literals after the preprocessor has looked for (and not found) trigraph sequences. Breaking string literals can also be useful when using numeric escapes that are followed by digits [e.g. if one wanted `"Hello"` followed by a zero byte followed by a digit 3', `"Hello\0""3"`. Incidentally for `?` one could either use `\x3F` followed by something other than a hex digit, or `\077`. – supercat Nov 16 '12 at 22:29