Preprocessor Directives and the Build Process

#ifdef vs #if defined()

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

Abstract art representing computer programming

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 ||.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved