24

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.

1 Answer 1

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

5
  • 3
    By 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. Oct 19, 2009 at 3:50
  • 2
    All about trigraphs: stackoverflow.com/questions/1234582/… Oct 19, 2009 at 5:36
  • 2
    You just ignore the existence of trigraphs... until they bite you in the ass. Oct 19, 2009 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). Oct 19, 2009 at 22:29
  • 1
    An 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, 2012 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.