Dietmar Kühl
Dietmar Kühl

Reputation: 153945

Why is the condition in this simple program ignored when a comment is present?

This simple program should clearly print nothing:

#include <iostream>
int main()
{
    // the condition below is ignored! \\
    if (false)
        std::cout << "hello, world\n";
}

However, compiling it prints hello, world (followed by a newline) with all compilers I tried it with (gcc, clang, Sun CC, xlC). When removing the comment, the program behaves as expected, i.e., the program doesn't print anything.

Why is the condition (always false) ignored with the comment present?

Upvotes: 3

Views: 143

Answers (3)

Alden
Alden

Reputation: 2269

The \\ is escaping the newline and is making the if (false) part of the comment.

As an explanation, the \ character at the end of a line in your c++ code signifies to the preprocessor that the next line is to be considered a continuation of the previous line. Because of this, \ is sometimes called the line continuation character. This often comes in handy for multi-line #defines.

#define MY_LONG_MACRO \
    for(int i = 0; i < 10; i++) \
    { std::cout << "multi-line macro"; }

Upvotes: 14

Raindrop7
Raindrop7

Reputation: 3911

that is because \ at the very end of line (no character even white spaces) is followed by means that next line is considered to be the completion of this one.

this generally used with strings eg:

string s = "sdgfdgfdgfdg\
       dssdfsdf";

if there's a white space after the single backslash above then you'll get a compile-time error.

you can add white space after it and everything will be ok eg:

// the condition below is ignored! \\[white space]
if (false)
    std::cout << "hello, world\n";

Upvotes: 0

alain
alain

Reputation: 12047

A single \ is a line-continuation character indicating the next line is part of this line. It does not matter how many \ there are, only the last one makes the next line part of the first line, the \ before are just a part of the comment.

Demo

Upvotes: 2

Related Questions