2

I was working in some running legacy C code compiled with C99 compiler and I encountered a '#' (hash symbol) on an otherwise empty line in the middle of a header file. I compile with -Wall, -Werrors, and -pedantic but get no complaint from the GCC compiler that runs my unit tests, or my target cross compiler. I did a quick google search of the BNF syntax of both the language and the pre-processor an could not figure out what should happen for a stray #. It happened to be in column 1 but if I move it to column 2 it still does not throw any warnings. My GCC compiler is gcc (Rev1, Built by MSYS2 project) 9.1.0.

Not a problem really, just unexpected.

Anyone have any insights?

cigien
  • 57,834
  • 11
  • 73
  • 112
bd2357
  • 704
  • 9
  • 17
  • 2
    Please don't add the c++ tag if you have a c question. If you do want to know the rules for c++, see https://stackoverflow.com/questions/62076620 The rules happen to be basically the same here since it involves the preprocessor, but you still shouldn't double tag these languages. – cigien Aug 04 '21 at 22:53
  • I think the C++ tag is appropriate here because we often use the #ifdef __cplusplus hack in our headers. (Pretty common in embedded frameworks) and the pre-processors are pretty close cousins. But thanks for the reminder. – bd2357 Aug 04 '21 at 23:16

1 Answers1

7

Question 0: “I encountered a '#' (hash symbol) on an otherwise empty line in the middle of a header file.”

C 2018 6.10.7 (“Null directive”) 1 says:

A preprocessing directive of the form

# new-line

has no effect.

Question 1: “It happened to be in column 1 but if I move it to column 2 it still does not throw any warnings.”

C 2018 6.10 2 says the # token for a preprocessing directive

… is either the first character in the source file (optionally after white space containing no new-line characters) or that follows white space containing at least one new-line character.

Thus, a # may appear after white space at the beginning of the file or after white space at the beginning of a new line.

Note that sequences of white space are largely outside the formal grammar of C (instead, they are addressed in text where necessary, as seen in the above), and they include comments that have been replaced by spaces earlier in processing. So preprocessing directives may also follow comments.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Cool, thanks for the ref. Never seen it before. – bd2357 Aug 04 '21 at 22:42
  • 2
    And, according to [§5.1.1.2 Translation phases](http://port70.net/~nsz/c/c11/n1570.html#5.1.1.2), comments are replaced by spaces in phase 3 and preprocessing directives are processed in phase 4, so comments can precede preprocessing directives on a line. – Jonathan Leffler Aug 04 '21 at 22:43