In C Language, the #if and #else directives are preprocessor directives used for conditional compilation.
They allow us to include or exclude sections of code based on the evaluation of constant expressions at compile-time.
#if constant_expression // Code to be compiled if constant_expression is true (non-zero) #else // Code to be compiled if constant_expression is false (zero) #endif
"constant_expression" is a constant expression that is evaluated at compile-time.
If the expression evaluates to non-zero (true), the code between "#if" and "#else" is included in the compilation.
Otherwise, the code between "#else" and "#endif" is included.
#include <stdio.h> #define DEBUG 1 int main() { #if DEBUG printf("Debugging information.\n"); #else printf("Release mode.\n"); #endif return 0; }
Debugging information.
the macro "DEBUG" is defined with a value of 1.
Therefore, the condition "#if DEBUG" evaluates to "true", and the debugging information message will be included in the compiled program.
If "DEBUG" were defined as 0 or not defined at all, the "#else" block would be compiled, and the "Release mode." message would be included.
#include <stdio.h> #define MAX_SIZE 100 #define ARRAY_SIZE 90 int main() { #if MAX_SIZE > ARRAY_SIZE printf("Max size is greater than array size.\n"); #else printf("Array size is greater than or equal to max size.\n"); #endif return 0; }
Max size is greater than array size.
the condition "#if MAX_SIZE > ARRAY_SIZE" is evaluated at compile-time.
If "MAX_SIZE" is greater than "ARRAY_SIZE", the first message will be printed; otherwise, the second message will be printed.
#include <stdio.h> #define USE_FEATURE_X int main() { #if defined(USE_FEATURE_X) printf("Feature X is enabled.\n"); #else printf("Feature X is not enabled.\n"); #endif return 0; }
Feature X is enabled.
if "USE_FEATURE_X" is defined, the code inside the "#if" block will be compiled, and "Feature X is enabled." will be printed.
Otherwise, the code inside the "#else" block will be compiled, and "Feature X is not enabled." will be printed.
"#if" and "#else" can be used for conditional compilation in C programming, allowing us to control which sections of code are included in the compiled program based on the evaluation of constant expressions.