Click here to Skip to main content
15,446,510 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
See title
what is the difference between if(0)  and #if 0 

What I have tried:

See title
what is the difference between if(0)  and #if 0 
Updated 7-Jan-22 20:16pm

if is part of the source code. if(0) would not execute the statement that follows, because 0 is interpreted as false. But it would always execute an else that matches the if.

#if is part of the preprocessor that modifies the source code before it is compiled. The code that follows an #if 0 would be excluded from the compile, but code that followed a matched #else (or #elif that evaluated to non-zero) would be compiled, up to the closing #endif.
Share this answer
Member 14968771 7-Jan-22 15:11pm    
So if(0) will compile what follows , but #if 0 will not. And #if(0) is same as $if 0. But id 0 will not compile.
Greg Utas 7-Jan-22 15:56pm     CRLF
#if(0) is the same as #if 0, but I don't know what $if 0 is. I think if(0) will compile what comes after the if, but you'll probably get a warning about unreachable code, and the compiler might be allowed to ignore that code. What id 0 has to do with this, I don't know. It won't compile.
The question has a complicated answer. Greg Utas is basically correct, but I'd like to add something.

With pretty much any C or C++ compiler, an if where the test expression is constant will NOT get compiled into the executable.

So, in the case of

if(0) printf("hello\r\n");

None of that code will wind up in the binary. The compiler removes it altogether.

Same if you fold constants, or otherwise use any formula where all the values are constant. If the compiler *can* resolve it at compile time, it basically will.

Now, the upshot of this is you can effectively do the same thing as #if 0 for code blocks without using the preprocessor. This is important when your test condition is not 0, but rather refers to some static const value somewhere. However, with the preprocessor you can #if out whole functions and classes, not just code blocks, if that makes sense.
Share this answer
if (0) is a general program control statement, while #if 0 is a precompiled control statement. One is run control and the other is compile control.

I can write
#if 0
lstat(file, st);
It can be compiled and passed under vc, but
if (0)
lstat(file, st);
It is impossible to let vc pass the compilation.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900