C++
Module 24: Preprocessor and MacrosIntermediate40 min read

C++ Preprocessor Directives, Conditional Compilation & Macro Pitfalls

Understand #define object/function macros, conditional compilation (#ifdef, #ifndef, #if), predefined macros (__LINE__, __FILE__), and why constexpr/inline beat macros.

Key Takeaways & Core Concepts
  • Understand #define object/function macros, conditional compilation (#ifdef, #ifndef, #if), predefined macros (__LINE__, __FILE__), and why constexpr/inline beat macros.
  • Practice writing and running standard examples.
  • Apply best practices and debugging techniques.

1. Preprocessor Directives & Conditional Compilation

The preprocessor runs before compilation: #include, #define, #undef, #ifdef, #ifndef, #if, #elif, #else, #endif. Predefined macros: __FILE__, __LINE__, __DATE__, __TIME__, __cplusplus.

1. Safe constexpr vs. Macro Pitfall
1#include <iostream>
2#define BAD_SQR(x) x * x
3constexpr int goodSqr(int x) { return x * x; }
4
5int main() {
6 std::cout << "BAD_SQR(2+3) = " << BAD_SQR(2 + 3) << "\n"; // 2 + 3*2 + 3 = 11!
7 std::cout << "goodSqr(2+3) = " << goodSqr(2 + 3) << "\n"; // 25
8 return 0;
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: Demonstrates why `constexpr` functions are strictly safer than `#define` macros.

2. Macro Pitfalls vs. Modern `constexpr` / `inline`

Function-like macros (#define SQR(x) x*x) lack type checking and evaluate arguments multiple times (SQR(i++) increments i twice!). Replace constant macros with constexpr and function macros with constexpr / inline functions.

Practice & AssessmentC++ Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)