rwallace
rwallace

Reputation: 33515

What exactly can you put after #if 0?

According to the C language standard, the lines between #if 0 and #endif are required only to contain preprocessing tokens, so most kinds of completely malformed syntax e.g. #foo or #include [bar] are allowed (silently ignored); GCC and Microsoft C++ do indeed silently ignore such.

An @ does not as far as I can see correspond to any preprocessing token so should still be a syntax error. GCC and Microsoft C++ silently ignore it. Is this effectively a language extension or am I missing something?

Does anyone actually use the ability to put malformed syntax between #if 0 and #endif in practice?

Upvotes: 8

Views: 883

Answers (3)

Pranit P Kothari
Pranit P Kothari

Reputation: 326

Code between #if 0 and #endif is not going to include in final source code (after per-processor output). If you are using Visual Studio and want to see pre-processor's output, Go to project property -> Select C/C++ -> Select Preprocessor -> Select 'Yes' in Preprocess to a file option.

Go to your project directory and you will see '.i' file. This is your preprocessor's output.

And you can see code between #if 0 and #endif is not included. So no question of error.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409442

The preprocessor is what is sounds like: It processes files before (pre) the compiler. The input the actual compiler sees is what the preprocessor feeds it, and if a part of the code is between #if 0 and a matching #endif, then the compiler won't even see that code. That is why you can put almost anything in that section, the compiler will simply not see it.

Upvotes: 2

Bart van Ingen Schenau
Bart van Ingen Schenau

Reputation: 15768

Both the C and C++ standard contain a special 'escape clause' in their grammar that makes that every non-white-space character is (part of) a preprocessing token. For this reason, whatever you put in a block between #if 0 and #endif can almost never cause a compilation error. The only exception are mismatched quotes for character and string literals.

And yes, I regularly put malformed syntax between #if 0 and #endif to disable some partially-written code.

Upvotes: 13

Related Questions