Escape Character
Filed under Programming
I ran across this today. It is subtle, but good to know.
An escape character (backslash '\') is handled in two ways in C++:
- 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...
#include "c:\test\newfile.h"
...would treat the backslashes as file separators instead of the escape sequence "\t" and "\n" because it is parsed by the preprocessor.
This line...
system("type c:\\test\\newfile.h");
...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'.
Comments (3)
Makes my head hurt.
Posted by bubba | June 6, 2007 7:42 AM
Posted on June 6, 2007 07:42
When I was learning C++ my favorite Escape Character was \a, very fun to make a loop of that and load the program on a friends computer.
ahh the fun....
although I still love C#'s way of referencing an assembly:
using Microsoft.Xna.Framework;
I know it is not the same thing but I still love it. Kinda reads like a sentence.
John
Posted by John Mark Roquemore | June 6, 2007 11:14 AM
Posted on June 6, 2007 11:14
Harry Houdini remains my favorite escape character.
Posted by Steve's Cat | June 6, 2007 2:41 PM
Posted on June 6, 2007 14:41