3

Is this a valid line of C++? What is it supposed to mean?

#

What about this one:

# // a comment

Recent compilers seem to ignore it without errors nor warnings.

Does it "do nothing"? I have a header file where a "compatibility" section bombs out when compiled with g++ 7.4.0 in presence of such lines. It doesn't seem to trip up compilers that see this line excluded in an inactive #if branch.

Note: gcc 7.4.0 on Debian Bionic (as of this writing) on Travis CI is tripped by such lines.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • As to why a compiler may "trip". Some text editors write text files without an end-of-line marker before the end-of-file marker. That can cause some older C or C++ preprocessors to not read the last line of the file. I recall a preprocessor adamantly failing to recognise an `#endif` (closing an include guard) that was visibly present when editing the file. The fix was an extra blank line (or line with a comment saying "don't remove this line") after that `#endif`. For info, see https://stackoverflow.com/questions/2287967/why-is-it-recommended-to-have-empty-line-in-the-end-of-a-source-file – Peter May 29 '20 at 10:14
  • @Peter Good tip! In my case, the `#` was well before the last line. – Kuba hasn't forgotten Monica May 29 '20 at 21:41
  • While the behaviour I described seems different, it is an example of the way content of a source/header file may appear correct, but trip up a preprocessor. Until it was isolated, the example I described caused headaches when the project source was copied between unix and windows machines (and run through `unix2dos()` or `dos2unix()`, depending on direction of copying), and then built. I can't help wondering if you've encountered another problem of that ilk - finding a "lower level" way of examining the file than a text editor may give some clues. – Peter May 30 '20 at 01:01
  • Oh not it’s just old gcc bugs, that’s all. – Kuba hasn't forgotten Monica May 30 '20 at 22:41

1 Answers1

8

Both examples are valid, and they do nothing.

For the second example, first the comments are removed in translation phase 3:

... Each comment is replaced by one space character. New-line characters are retained. ...

which results in the first case, which is a preprocessor directive that is expanded in translation phase 4:

Preprocessing directives are executed, ...

This preprocessor directive is valid, and is called a Null directive, and has no effect, as stated here:

A preprocessing directive of the form

# new-line

has no effect.

where new-line is literally the new-line character.

So the code you have shown is valid, and should be accepted by a conforming implementation.

Community
  • 1
  • 1
cigien
  • 57,834
  • 11
  • 73
  • 112