C #ifndef
Syntax
#ifndef identifier
// code to be included if identifier is not defined
#endif
Example
#ifndef PI
#define PI 3.1415926535897
#endif
#include <stdio.h>
int main() {
double radius = 2.5;
printf("Area of the circle is: %f", radius * radius * PI);
return 0;
}
Output
Area of the circle is: 19.634956
Explanation
#ifndef
is a C preprocessor directive that checks whether a given identifier has been defined before inclusion of a certain block of code. The block of code between #ifndef
and #endif
is included only if the identifier has not been defined.
In the above example, the identifier PI
is defined only if it was not defined before. This ensures that the value of PI is defined only once in the program, regardless of how many times the header file containing the definition is included.
Use
The #ifndef
directive is commonly used to prevent multiple definitions of a variable, constant or function prototype. By surrounding the definition of the identifier with #ifndef
and #endif
, the code block is included only if the identifier is not already defined.
Important Points
- The
#ifndef
directive checks whether an identifier has been defined before its inclusion in a program. - The code between
#ifndef
and#endif
is included only if the identifier has not been defined. #ifndef
is often used with#define
to define constants that should only be defined once.#ifndef
can also be used to include header files, with the header file contents between#ifndef
and#endif
guards to prevent multiple inclusion.
Summary
The C #ifndef
directive is a valuable tool for preventing multiple definitions of a variable, constant or function prototype. It allows code blocks or header files to be included only once in a program, reducing the possibility of naming conflicts and memory leaks. It is important to use #ifndef
directives with #define
statements to define constants and to place header file contents between #ifndef
and #endif
guards. This ensures that header files are included only once, improving program efficiency and avoiding potential issues.