#elifdef and #elifndef in C++ 23
Last Updated :
17 Dec, 2023
In C++, we can use the #ifdef, and #ifndef preprocessor directives to add the conditional code to our program. The C++ preprocessor processes this code instead of the compiler. The C++ 23 standard introduces two more such preprocessor directives #elifdef and #elifndef to further make the conditional compilation more powerful. In this article, we will discuss these two new addition to the C++ preprocessor directives list.
#elifdef in C++
The #elifdef directive is used in conjunction with the #ifdef directive and is used to check if a specified identifier has been defined as a macro name. If the identifier is defined, the statements inside this block are executed. It can be viewed as “else if defined?”.
Syntax of #elifdef
#ifdef some_MACRO
// CODE
#elifdef MACRO_NAME
// CODE
#endif
We can add more #elifdef directives in the above syntax making it similar to the if-else-if ladder.
C++
#include <iostream>
using namespace std;
#define MAX 222
int main()
{
#ifdef MIN
cout << "MIN is defined." << endl;
#elifdef MAX
cout << "MAX is defined." << endl;
#else
cout << "Nothing is defined." << endl;
#endif
cout << "Value of MAX: " << MAX << endl;
return 0;
}
|
Output
MAX is defined.
Value of MAX: 222
Explanation
MAX macro is defined with value 222 but MIN is not defined. So the blocks of #ifdef MIN will not be executed. But the block of #elifdef will be executed as we can see in the output.
#elifndef in C++
The #elifndef directive is similar to the #elifdef in a way that both of these check if the specified macro is defined or not. But this macro executes its block if the macro is not defined. It can be viewed as “else if not defined?”.
Syntax of #elifndef
#ifdef some_MACRO
// CODE
#elifndef MACRO_NAME
// CODE
#endif
Example of #elifndef
The below code demonstrates the use of the #elifndef directive.
C++
#include <iostream>
using namespace std;
int main()
{
#ifdef MIN
cout << "MIN is defined." << endl;
#elifdef MAX
cout << "MAX is defined." << endl;
#elifndef MAX
#define MAX 222
#else
cout << "Nothing is defined." << endl;
#endif
cout << "Value of MAX: " << MAX << endl;
return 0;
}
|
Output
Value of MAX: 222
Explanation
In this code, MAX and MIN macros are not defined, so the #ifdef directive will be evaluated as false, the #elifdef will also be evaluated false but the #elifndef will be evaluated as true and the MAX macro will be defined as we can see in the output.
Share your thoughts in the comments
Please Login to comment...