Preprocessor – Understanding the defined Operator

This is the least known of the preprocessor operators. The other two operators are the token pasting operator (##) and the stringizing operator (#).

The behaviour is the same for both C and C++ compilers.

Format

defined macro_name

or

defined ( macro_name )

Use

The defined operator is used to check if a macro_name has been defined or not. If the macro_name exists, it does not evaluate the macro.

If the macro_name exists, then defined macro_name is replaced with the value 1 (one), otherwise, it is replaced with the value 0 (zero).

The defined operator may only be used with the #if and #elif preprocessor directives.

The expression:

#if defined MY_MACRO

has the same effect as:

#ifdef MY_MACRO

The expression:

#if !defined MY_MACRO

has the same effect as:

#ifndef MY_MACRO

The expression:

#if defined MY_MACRO && defined MY_OTHER_MACRO

has the same effect as:

#ifdef MY_MACRO
# ifdef MY_OTHER_MACRO

The following expression is much harder to express cleanly using #ifdef or #ifndef directives:

#if defined MY_MACRO || defined MY_OTHER_MACRO

A possible way to express it using #ifdef would be:

// if MY_MACRO exists, we don't care about MY_OTHER_MACRO
#ifdef MY_MACRO
.
.
.
// statements to process
.
.
.
#endif
// if MY_MACRO doesn't exist, then we need to check
// if MY_OTHER_MACRO exists
#ifndef MY_MACRO
# ifdef MY_OTHER_MACRO
.
.
.
//duplicate statements to process
.
.
.
#endif

Which results in duplicated statements. This means the code is more prone to errors changes in one piece of code must be made in other places.

Leave a Reply

Your email address will not be published. Required fields are marked *