Tuesday 6 March 2012

Backslash Line Splicing in C & C++


I was playing around with some code in Visual C++ 2010 and at one point I typed a backslash key. The result surprised me.

Here’s an example of what I had:

// Some comment about main function.
int main()
{

Here’s what happened when I added a backslash at the end of the comment.

// Some comment about main function.\
int main()
{

The int main function turned green meaning it was commented. The program wouldn’t compile. I got this error message: error C2447: '{' : missing function header
 
What was going on?

If I removed the backslash, everything was fine. If I added other characters after the backslash, everything was fine. It had nothing to do with the backslash used in escape sequences and the reference material on adding comments to C or C++ code didn’t discuss a backslash, it was the slash character.

A quick search or two revealed the answer in something called line splicing.

In Appendix A.12 of K&R they write:

Each occurrence of a backslash character \ followed by a newline is deleted, this splices lines.

When you compile your source files, the compiler executes a pre-processing stage where comments are removed and lines with the backslash and newline characters are deleted.

Another lesson learnt in the world of coding.


No comments:

Post a Comment