#ifdef vs #if defined()

What is the difference between #ifdef and #if defined() in C++?

Both #ifdef and #if defined() are used for conditional compilation in C++, but they have a slight difference in syntax.

The #ifdef MACRO checks if MACRO is defined. If it is, the code block following the directive is included in the compilation.

#include <iostream>
#define DEBUG

int main() {
#ifdef DEBUG  
  std::cout << "Debug mode is on\n";
#endif
}
Debug mode is on

#if defined(MACRO) also checks if MACRO is defined, but it allows for more complex expressions.

#include <iostream>
#define DEBUG

int main() {
#if defined(DEBUG) && !defined(RELEASE)  
  std::cout << "Debug mode is on,"
    " Release mode is off\n";
#endif
}
Debug mode is on, Release mode is off

In most cases, #ifdef and #if defined() can be used interchangeably. However, #if defined() provides more flexibility when combining multiple conditions using logical operators like && and ||.

Preprocessor Directives and the Build Process

Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Defining Macros with Arguments
How can I define a macro that takes arguments in C++?
Preventing Multiple Header Inclusion
What are the best practices to prevent multiple inclusion of header files?
Using #ifdef for Platform-Specific Code
How can I use #ifdef to write platform-specific code in C++?
Defining Constants with #define
Should I use #define to define constants in C++?
Using #pragma once in Header Files
What are the advantages of using #pragma once in header files?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant