简体   繁体   中英

Is the use of unknown escape sequence invokes undefined behavior in C++?

Consider following program:

#include <iostream>
int main()
{
     std::cout<<"Can this lead to undefined behavior?"<<'\s';
}

g++ gives an warning:

[Warning] unknown escape sequence: '\s' [enabled by default]

Here '\\s' in typed accidentally instead of '\\n' . So, is this program well defined or undefined? What C++ Standard says about this? The C Programming language by K&R says that it is undefined behavior in C.

(N3337 [lex.ccon]/3): Escape sequences in which the character following the backslash is not listed in Table 7 are conditionally-supported, with implementation-defined semantics.

This means that non-standard escape sequences are valid if your implementation supports them. Check the documentation for your particular implementation for the semantics of any additional characters.

No, by the standard the '\\s' is not allowed. Between the ' es you have to have a sequence of c-characters which are either escape-sequence s, universal-character-name s or characters other than single quote ( ' ), backslash ( \\ ) or newline character.

That your compiler accepts it (which it according to the standard is allowed to do if it documents it) is another question and you should consult your compiler documentation for information on how it interpret's it (or stop writing non-conforming code).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM