Introduction
In the C programming language, the #ifndef directive helps us allow the conditional compilation. The preprocessor of C programming helps determine if the macro provided has not existed before, including the specific subsequent code in the C compilation process. #ifdef preprocessor checks whether the particular macro is not defined with the help of the #define directive. Now, if the condition is TRUE, it will help to execute the code, and if the state is FALSE, the else code of the #ifdef will be compiled or executed.
Syntax
#ifdef MACRO
// code inside
#endif
Syntax with #else
#ifdef MACRO
//successful code will get executed
#else
// else code will get executed
#endif
Syntax for #ifdef directive
#ifdef MACRO
//Code Statements
#else
//Code Statements which are used to include if the specific token is defined
#endif
Certain essential things related to the parameters mentioned in the syntax above are:
- #ifdef MACRO - We must not define the directive if the preprocessor wants to include the source code during the compilation.
- #else directive - In case the #ifdef directive does not accept, then else code statements will be printed which are actually used while including the specific which is defined.
- #endif directive - The #ifdef should permanently be closed by an #endif directive. Otherwise, an error shall be encountered.
Example 1
Code
#include <conio.h>
#include <stdio.h>
#define INPUT
void main() {
int b1=0;
#ifndef INPUT
b1=2;
#else
printf("Enter b1 value :: ");
scanf("%d", &b1);
#endif
printf("The value of b1 :: %d\n", b1);
}
Explanation
Here we firstly load a few of the libraries like “conio.h” and “stdio.h” are used, then we define the directive to be used as the MACRO value as INPUT. Then we define the main function, where the #ifdef preprocessor is used with the macro definition as INPUT, and then b1 variable value is stored with the value “2” and then the else directive.
Output
Enter b1 value :: 10
The value of b1 :: 10