Code blocks between #if 0 and #endif should have double double quotes?

int main(void) { #if 0 something" #endif return 0; } 

The simple program above generates a warning: missing terminating " character in gcc. This seems strange because it means that the compiler allows code blocks between #if 0 and endif have an invalid statement, such as something , but not double quotes " that do not match. The same thing happens when using #ifdef and #ifndef .

These comments are in order:

 int main(void) { /* something" */ return 0; } 

Why? And the single quote ' behaves the same way, are there any other tokens that are specially processed?

+7
source share
4 answers

See frequently asked questions comp.Lang.c, 11.19 :

In ANSI C, the text inside the “off” #if, #ifdef or #ifndef must still consist of “valid preprocessing tokens”. This means that the characters "and" should be combined in the same way as in real C-code, and pairs should not cross the boundaries of the lines.

+9
source

Compilation has to go through many cycles before generating an executable binary.

You are not in the compiler yet. This preprocessor is flagged with this error. This will not check the syntax of the C language, but the missing quotation marks, curly braces and the like are errors before the processors.

After this pre-processor, your code will go to the C compiler, which will detect the error you expect ...

+2
source

The preprocessor runs at the token level, and the string literal is considered the only token. The preprocessor warns you about the presence of an invalid token.

According to the C99 standard, a pre-processing token is one of the following things:

  • header name
  • identifies er
  • pp number
  • character constant
  • literal string
  • punctuator
  • each non-white space character that cannot be one of the above

The standard also states:

If the “or” symbol matches the last category, undeformed behavior is defined.

Things like the “statement” above are not valid for the C compiler, but it is a valid token, and the preprocessor removes that token before it gets to the compiler.

+1
source

Besides Kevin's answer, GCC Incompatibility says:

GCC complains of inexhaustible character constants within preprocessing conditions that fail. Some programs contain comments in English in conditional expressions that are guaranteed to fail; if these comments contain apostrophes , GCC will probably report an error. For example, this code will result in an error:

 #if 0 You can't expect this to work. #endif 

The best solution to this problem is that the text is placed in the actual C comment, limited to /*...*/ .

0
source

All Articles