Monday, December 29, 2008

[C/C++] Using continuation character \

You can use the backslash (\) as a continuation character. When a newline character (equivalent to pressing the RETURN key) immediately follows the backslash, the compiler ignores the backslash and the newline character and treats the next line as part of the previous line. This is useful primarily for preprocessor definitions longer than a single line. For example:
#define assert( exp ) \

((exp) ? (void) 0:_assert( #exp, __FILE__, __LINE__ ))


Above example may be ok but consider if it is a string which was separated by \ in two lines what will be the result ?
See the below example. Consider replacing /*Use empty space*/ with a set of empty spaces of that length.

Code:
OutputDebugString( "This is a very long \
/*Use empty space*/string." );

Output:
This is a very long /*Use empty space*/string.

See the gap in between "long string" its nothing but the space in the second line's begining to "string". We have compromised the output beauty for the code beauty. If you have used the code as shown below then output will look fine but about the code beauty, code alignment & code readability.

OutputDebugString( "This is a very long \
string." );


Output:

This is a very long string.

But I know what you will be looking for is both the code beauty (alignment) with expected output. Then here is the optimal solution for using strings split in to two lines. Close double quotes (") when the line ends and keep the string in next line inside the double quotes.

Code:
OutputDebugString( "This is a very long "
/*Use empty space*/"string." );

Output:
This is a very long string.


2 comments:

Unknown said...

http://stackoverflow.com/a/10045867/1343222

Anonymous said...

Good info��