In C Language, the "#ifndef" directive is another preprocessor directive used for conditional compilation, similar to "#ifdef". #ifndef stands for "if not defined" and is used for conditional compilation.
However, "#ifndef" checks if a particular macro has not been defined.
If the specified macro is not defined, the code between "#ifndef" and "#endif" will be included in the compilation.
#ifndef macro_name // Code to be compiled if macro_name is not defined #endif
#include <stdio.h> #ifndef DEBUG_MODE #define DEBUG_MODE #endif int main() { #ifndef DEBUG_MODE printf("Debug mode is disabled.\n"); #else printf("Debug mode is enabled.\n"); #endif printf("Normal execution.\n"); return 0; }
we're checking whether "DEBUG_MODE" is not defined using "#ifndef".
If "DEBUG_MODE" is not defined, it will be defined using "#define DEBUG_MODE".
Then, the code inside "#ifndef DEBUG_MODE" and "#else" blocks will include the debug mode message during compilation.
#ifndef DEBUG_MODE #define LOG(msg) printf("DEBUG Mode Disabled: %s\n", msg) #else #define LOG(msg) printf("DEBUG Mode Enabled: %s\n", msg) #endif int main() { LOG("This is a log message."); return 0; }
Here, we are checking `DEBUG_MODE` macro is not defined using the `#ifndef` Directive and the condition met true.
It executing `if` condition `#define LOG(msg) printf("DEBUG Mode Disabled: %s\n", msg)`.
DEBUG Mode Disabled: This is a log message.
#include <stdio.h> #define DEBUG_MODE #ifndef DEBUG_MODE #define LOG(msg) printf("DEBUG Mode Disabled: %s\n", msg) #else #define LOG(msg) printf("DEBUG Mode Enabled: %s\n", msg) #endif int main() { LOG("This is a log message."); return 0; }
In this example, we define the `DEBUG_MODE` macro using the `#define` directive before checking `#ifndef`.
so if we check condition `ifndef` DEBUG_MODE it becomes false and code fall to else condition.
it execute else condition `#define LOG(msg) printf("DEBUG Mode Enabled: %s\n", msg)`.
DEBUG Mode Enabled: This is a log message.
"#ifndef" is commonly used for conditional compilation to include specific sections of code only if certain macros are not defined.
It's particularly useful for guarding against multiple inclusions of header files.