#ifdef and #ifndef
#ifdef and #ifndef are preprocessor directives in C and C++ that are used for conditional compilation, which allows developers to include or exclude code from the final executable based on certain conditions.
The directives #ifdef and #ifndef provide an alternative short form for combining #if with the defined operator.
#if defined(macro_name )
is equivalent to #ifdef macro_name
#if !defined(macro_name )
is equivalent to #ifndef macro_name
Syntax of #ifdef -
#ifdef macro name
.................
#endif
If the macro_name has been defined with the #define directive, then the statements between #ifdef and
#endif will be compiled.
If the macro_name has not been defined or was undefined using #undef, these statements are not compiled.
Syntax of #ifndef -
#ifndef macro_name
.....................
#endif
If the macro_name has not been defined using #define or was undefined using #undef, then the statements
between #ifndef and #endif are compiled.
If the macro_name has been defined, then these statements are not compiled.
Let us take a program-
#include #define TEST
int main() {
#ifdef TEST
printf("The macro TEST is defined!\n");
#endif
#ifndef TEST2
printf("The macro TEST2 is not defined!\n");
#endif
return 0;
}
In this example, the macro TEST is defined using #define, so the code within the #ifdef block will be compiled and the output will be: "The macro TEST is defined!"
.
#ifndef, on the other hand, tests whether a particular macro is not defined. If the macro is not defined, the code within the #ifndef block will be compiled, otherwise, it will be skipped.
Here is an example -
#include //#define TEST
int main() {
#ifdef TEST
printf("The macro TEST is defined!\n");
#endif
#ifndef TEST2
printf("The macro TEST2 is not defined!\n");
#endif
return 0;
}
In this example, the macro TEST is commented out using //, so it is not defined.
The code within the #ifndef block will be compiled, and the output will be: "The macro TEST is not defined!"
and "The macro TEST2 is not defined!"
.
If we uncomment the #define TEST line, the output will be only "The macro TEST2 is not defined!"
.