C Programming Tutorial
Description
In the C Programming Language, the #ifndef directive allows for conditional compilation. The preprocessor determines if the provided macro does not exist before including the subsequent code in the compilation process.
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.
Syntax:
#ifndef MACRO
//code
#endif
Syntax with #else:
#ifndef MACRO
//successful code
#else
//else code
#endif
Note
The #ifndef directive must be closed by an #endif directive.
C #ifndef example
Let's see a simple example to use #ifndef preprocessor directive.
#include <stdio.h>
#include <conio.h>
#define INPUT
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Enter a:5
Value of a: 5
But, if you don't define INPUT, it will execute the code of #ifndef.
#include <stdio.h>
#include <conio.h>
void main() {
int a=0;
#ifndef INPUT
a=2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
Output:
Value of a: 2
Example
The following example shows how to use the #ifndef directive in the C language:
/* Example using #ifndef directive by C programming */
#include <stdio.h>
#define YEARS_OLD 15
#ifndef YEARS_OLD
#define YEARS_OLD 10
#endif
int main()
{
printf("C programming is over %d years old.\n", YEARS_OLD);
return 0;
}
In this example, if the macro YEARS_OLD is not defined before the #ifndef directive is encountered, it will be defined with a value of 10.
Here is the output of the executable program:
C programming is over 15 years old.
If you remove the line #define YEARS_OLD 15, you will see the following output from the executable program:
C programming is over 10 years old.