What is the #ifdef directive in C?
The #ifdef is one of the widely used directives in C. It allows conditional compilations. During the compilation process, the preprocessor is supposed to determine if any provided
Syntax
#ifdef `macro_definition`
macro_definition: We must not define the directive if the preprocessor wants to include the source code during compilation.
The
#ifdefdirective must always be closed by an#endifdirective; otherwise it will cause an error.
Code
Let’s look at an example where we define a macro xyz with the value 10. Now, when we reach line 11, we encounter the #ifdef condition. This statement determines whether or not xyz macro is defined.
For this example, we defined the xyz macro so the #ifdef condition is executed. If xyz were not defined, #else condition would have been executed.
#include <stdio.h>// define a macro#define xyz 10int main(){// use conditional if-defined statement// in this example, xyz is defined so we will execute// the printf part of #ifdef#ifdef xyzprintf("Your lottery number is %d.\n", xyz);#elseprintf("error printing lottery number");#endifreturn 0;}
Now, if you remove the #define xyz 10 statement, this will mean xyz is not defined. The #ifdef fails and printf inside the #ifdef is not executed (see code below):
#include <stdio.h>int main(){// use conditional if-defined statement// in this example, xyz is not defined so we will not execute// the printf part of #ifdef, #else is executed.#ifdef xyzprintf("Your lottery number is %d.\n", xyz);#elseprintf("error printing lottery number");#endifreturn 0;}
Free Resources