« Sarah Silverman | Home | Who knew? Hitler is a gamer! »

Individual Entry With Comments

June 6, 2007

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++:

  1. The C++ preprocessor ignores escape characters
  2. 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'.

The more you know!


Comments (3)


Makes my head hurt.

John Mark Roquemore:

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.


Harry Houdini remains my favorite escape character.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)


This page contains a single entry from the blog posted on June 6, 2007 1:03 AM.

The previous post in this blog was Sarah Silverman.

The next post in this blog is Who knew? Hitler is a gamer!.

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.34