In the C Programming Language, the #ifndef directive checks if the given token has been #defined earlier in the C code. If the token has not been defined earlier then it includes the code between #ifndef and #else. If no #else is present then code between #ifndef and #endif is included.
The both #ifndef and #define directives are known as header guards or #include guard in C/C++. They are used to prevent multiple declarations of variables and other data types and header files from being included multiple times. The #ifndef also prevents recursive inclusions of header files. Another non-standard preprocessor directive named #pragma once is widely used to force the inclusion of a header file only once.
The syntax of using #ifndef is as below:
1 2 3 4 | #ifndef #define // some code declarations #endif |
Use of #ifndef and #define
Here is a rather complete C program to demonstrate the use of #ifndef and #define.
1 2 3 4 5 6 7 8 9 10 11 12 | #include <stdio.h> #ifndef INTEREST_RATE #define INTEREST_RATE 8 #endif int main() { printf("Current Interest Rate is %d percent.\n", INTEREST_RATE ); return 0; } |
The output of the above C program is:
1 | Current Interest Rate is 8 percent. |
Here is a another C program to demonstrate the use of #ifndef and #define. As INTEREST_RATE is already defined so #ifndef does not execute.
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> #define INTEREST_RATE 9 #ifndef INTEREST_RATE #define INTEREST_RATE 8 #endif int main() { printf("Current Interest Rate is %d percent.\n", INTEREST_RATE ); return 0; } |
The output of the above program is:
1 | Current Interest Rate is 9 percent. |