1

Consider this:

#ifndef GUARD_H
#define GUARD_H
...
#endif GUARD_H

rather than:

#ifndef GUARD_H
#define GUARD_H
...
#endif // GUARD_H

Often I see at the #endif an 'identifier' commented out but without commenting it it still works.

Is everything after the #endif ingnored or...?

4

1 回答 1

11

No, this is not valid C++: it is ill-formed. There can be no tokens between the # endif and the newline that terminates the preprocessing directive line.

If you want to restate the condition from the #if directive, you can do so in a comment:

#endif // GUARD_H

However, this is really just redundant, especially for inclusion guards: if it's the last #endif in a header file, it's almost certainly there to end the #ifdef used at the top to prevent multiple inclusion, no?

In other places where you may have multiple nested levels of conditional directives, this might be useful, but even then it is often preferable to refactor the code to make it simpler or more straightforward.

于 2011-02-17T15:25:45.890 回答