Why does the statement “cout << '\\\\';” not fail?
Asked Answered
G

1

14

The source code is as the following.

cout << '\\' << endl;  //OK, output is \  
cout << '\\\\' << endl;  //OK, output is an integer 23644, but why? 

The statement cout << '\\\\' << endl; invokes the following function of class ostream.

_Myt& __CLR_OR_THIS_CALL operator<<(int _Val)

I know it is strange to write the expression '\\\\', But I don’t understand why it doesn’t fail. How to explain the result?

Galatea answered 8/4, 2016 at 9:23 Comment(4)
What do you mean by "fail"? Do you think it should fail to compile? If so, with what error? It's not clear why you find this behavior unexpected.Pasadena
See https://mcmap.net/q/109989/-why-do-multicharacter-literals-exist-in-c-and-c/2491746 for more discussion.Eldon
I like asking this question on the interviews.Oliveolivegreen
Got it, thank you very much. @Simple.Galatea
E
15

This is a multicharacter literal and has type int.

[lex.ccon]/2:

An ordinary character literal that contains more than one c-char is a multicharacter literal. A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the execution character set, is conditionally-supported, has type int, and has an implementation-defined value.

You should use "\\\\", which is char const[3]: two \ and a NUL byte at the end.

Eldon answered 8/4, 2016 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.