Both, C and C++, support an seemingly equivalent set of escape sequences like \b, \t, \n, \" and others starting with the backslash character (\). How is a backslash handled if normal character follows? As far as I remember from several compilers the escape character \ is silently skipped. On cppreference.com, I read these articles
I only found this note (in the C article) about orphan backslashes
ISO C requires a diagnostic if the backslash is followed by any character not listed here: [...]
above the reference table. I had also a look an some online compilers
C demo
#include <stdio.h>
int main(void) {
// your code goes here
printf("%d", !strcmp("\\ x", "\\ x"));
printf("%d", !strcmp("\\ x", "\\\ x"));
printf("%d", !strcmp("\\ x", "\\\\ x"));
return 0;
}
C++ demo
#include <iostream>
#include <string>
using namespace std;
int main() {
cout << (string("\\ x") == "\\ x");
cout << (string("\\ x") == "\\\ x");
cout << (string("\\ x") == "\\\\ x");
return 0;
}
Both treat "\\ x" and "\\\ x" as equivalent, (kind of) warning via syntax highlighting. IOW "\\\ x" has been transformed into "\\ x".
Can I assume this to be defined behavior?
Clarification (edit)
- I'm not asking about obviously invalid string literals like
"\". - I'm aware that an orphan backslash is somewhat problematic.
- I want to know if the result, the constant built by the compiler, is defined.
Edit #2: Focus even more on constant being generated (and portability).