0
0
CppConceptBeginner · 3 min read

What is Macro in C++: Definition and Usage Explained

In C++, a macro is a preprocessor directive that defines a piece of code or value to be replaced before compilation. It uses #define to create symbolic names or code snippets that the compiler substitutes directly in the source code.
⚙️

How It Works

A macro in C++ works like a shortcut or a label for code or values. Before the program is compiled, the preprocessor scans the code and replaces every macro name with its defined content. This is similar to using a sticky note to replace a long phrase with a short word everywhere in a document.

For example, if you define a macro for the number 10, every time you write that macro name in your code, the preprocessor swaps it with 10. This happens before the actual compilation, so the compiler only sees the replaced code. Macros can also include code snippets, making them powerful but sometimes tricky if overused.

💻

Example

This example shows a macro defining a constant value and a macro that acts like a simple function to add two numbers.

cpp
#include <iostream>

#define PI 3.14
#define ADD(x, y) ((x) + (y))

int main() {
    std::cout << "Value of PI: " << PI << "\n";
    std::cout << "Sum of 5 and 3: " << ADD(5, 3) << "\n";
    return 0;
}
Output
Value of PI: 3.14 Sum of 5 and 3: 8
🎯

When to Use

Macros are useful when you want to define constants or small reusable code snippets that the compiler replaces directly. They help avoid repeating the same value or code multiple times, making updates easier.

However, modern C++ prefers const variables and inline functions for safety and clarity. Use macros mainly for conditional compilation or when you need code that the compiler cannot handle directly, like including debug code or platform-specific instructions.

Key Points

  • Macros are replaced by the preprocessor before compilation.
  • They can define constants or code snippets.
  • Macros do not have type safety, so use carefully.
  • Modern C++ favors const and inline over macros for most cases.
  • Macros are useful for conditional compilation and platform-specific code.

Key Takeaways

Macros replace code or values before compilation using #define.
They help avoid repetition but lack type safety.
Prefer const variables and inline functions in modern C++.
Use macros mainly for conditional or platform-specific code.
Macros are powerful but should be used carefully to avoid bugs.