Are comments allowed on the same line as the preprocessor directives, and what is their meaning in this case?

I am thinking of something like this:

#include <iostream> // Comment 

Well, cppreference.com ( http://en.cppreference.com/w/cpp/preprocessor ) states that:

Preprocessing directives control preprocessor behavior. Each directive takes one line and has the following format:

# preprocessing character (one of define, undef, include, if, ifdef, ifndef, else, elif, endif, line, error, pragma) arguments (depends on the instruction) line break

So, a complete specification is given for the entire line, and there is no room for comment. Comments are not allowed on these lines.

However, both g ++ and clang ++ accept such input even with -Wall -Wextra -Wpedantic. Also cplusplus.com offers examples of such comments: http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

I am even more confused by the fact that someone told me that "it is still fair to leave comments in # lines, but they may not mean what you want." I'm not sure how this could be so, as per http://en.cppreference.com/w/cpp/language/translation_phases comments are replaced with space characters before starting the preprocessor, so if they are allowed on # lines, how can they interfere with the semantics of such a line?

+6
source share
1 answer

As indicated in the translation phases document that you contacted: Comments are replaced by a space in step 3 of phase 3. The preprocessor is executed in phase 4.

Thus, by the time the preprocessor processes the # lines, the comments turn into spaces, which usually do not affect the behavior of the preprocessing directives.

+10
source

All Articles