C #ifdef
0 183
The #ifndef directive in C stands for "if not defined."
It's another form of conditional compilation that checks if a particular macro is not defined.
This directive is commonly used in conjunction with #ifdef to prevent multiple inclusions of header files, known as header guards.
syntax of #ifndef in C
#ifndef macro_name // code to be compiled if macro_name is not defined #endif
Example:
//Program for #ifndef in C #includeint main() { #ifndef DEBUG printf("Debugging is disabled.\n"); #endif printf("This line is always printed.\n"); return 0; }
Output:
Debugging is disabled. This line is always printed.
In this example:
The DEBUG macro is defined only if it's not already defined.
The #ifndef DEBUG directive checks if DEBUG is not defined.
If DEBUG is not defined, the message "Debugging is disabled." is printed.
The message "This line is always printed." is printed regardless of whether DEBUG is defined or not.
Uses of #ifndef in C
Header Guards: To prevent multiple inclusions of header files, which can lead to redefinition errors.
#ifndef HEADER_FILE_H #define HEADER_FILE_H // Header file content #endif
Feature Toggles: Similar to #ifdef, it can be used to enable or disable certain features of the program based on configuration.
#ifndef FEATURE_A // Code related to Feature A if it's not enabled #endif
Conditional Compilation: To conditionally include or exclude code sections based on whether a macro is defined or not.
#ifndef LINUX // Code that's not specific to Linux #endif
Using #ifndef ensures that the code within the directive is only compiled if the specified macro is not defined, making it a useful tool for organizing and managing code in C programs.
Share:
Comments
Waiting for your comments