"if " and " #if "; which one is better to use
we could not say which better to use, because one is used in the compilation phase (#if
) and the other one is used in the runtime phase(if
)
#if 1
printf("this code will be built\n");
#else
printf("this code will not\n");
#endif
try to build the above code with gcc -E
and you will see that your compiler will generate another code containing only :
printf("this code will be build\n");
the other printf will not be present in the new code (pre processor code) and then no present in the program binary.
Conclusion: the #if
is treated in the compilation phase but the normal if
is treated when your program run
You can use the #if 0
in a part of your code inorder to avoid the compiler to compile it. it's like you have commented this part
example
int main(void) {
printf("this code will be build\n");
#if 0
printf("this code will not\n");
#endif
}
it's equivalent to
int main(void) {
printf("this code will be built\n");
/*
printf("this code will not\n");
*/
}
if
and #if
are different things with different purposes.
If you use the if
statement, the condition is evaluated at runtime, and the code for both branches exists within the compiled program. The condition can be based on runtime information, such as the state of a variable. if
is for standard flow control in a program.
If you use the preprocessor's #if
, the condition is evaluated at compile-time (originally this was before compile-time, but these days the preprocessor is usually part of the compiler), and the code for the false branch is not included in the compiled program. The condition can only be based on compile-time information (such as #define
constants and the like). #if
is for having different code for different compile-time environments (for instance, different code for compiling on Windows vs. *nix, that sort of thing).