The #ifndef
directive is one of the widely used used directives in C. It allows conditional compilations. During the compilation process, the preprocessor is supposed to determine if any provided
#ifndef `macro_definition`
// macro_definition must not be defined if the preprocessor wants to include the source code during compilation.
The
#ifndef
directive must always be closed by an#endif
directive, otherwise it will cause an error.
Example of the use of #ifndef
in C:
#include <stdio.h>// we define a variable#define xyz 32int main(){// now we use #ifndef to see if xyz is defined or not// in this example, it is defined, we ll move to the// #else part of the code.#ifndef xyzprintf("Error printing lottery number");#elseprintf("Your lottery number is %d", xyz);#endifreturn 0;}
The output:
Your lottery number is 32
Now let’s remove the #define xyz 32
statement in the code:
#include <stdio.h>int main(){// now we use #ifndef to see if xyz is defined or not// in this example, it is not defined, we ll move to the// #ifndef execution of the code.#ifndef xyzprintf("Error printing lottery number");#elseprintf("Your lottery number is %d", xyz);#endifreturn 0;}
Free Resources