Filed under Programming
I ran across this today. It is subtle, but good to know.
- The C++ preprocessor ignores escape characters
- The C++ compiler respects escape character
In Windows, the backslash has a dual use: it is used to separate files and directories and it is an escape character. This can lead to confusion.
So this line...
...would treat the backslashes as file separators instead of the escape sequence "\t" and "\n" because it is parsed by the preprocessor.
...requires two backslashes because it is handled by the C++ compiler. The "\\" is an escape sequence for a single backslash (a complete list of escape sequences is here). If you only used single backslashes, the "\t" would be treated as a tab and the "\n" would be treated as a newline.
Now, just to make it a bit more confusing, consider this...
#define COMMAND "type c:\\test\\newfile.h"
system( COMMAND );
...you have to use two slashes because the preprocessor will just replace 'system( COMMAND )' with 'system( "type c:\\test\\newfile.h" )', which will be processed by the C++ compiler and thus respects escape characters.
So...backslashes are always treated as escape characters EXCEPT when they are used by the preprocessor exclusively (i.e. the compiler never sees them) like the preprocessor directive '#include'.