0
0
CppHow-ToBeginner · 3 min read

How to Use #define in C++: Syntax and Examples

In C++, #define is used to create macros or constants by defining a name that the preprocessor replaces with a value or code before compilation. It works by simple text substitution and does not respect C++ types or scopes.
📐

Syntax

The #define directive has two main forms:

  • Constant definition: #define NAME value replaces all occurrences of NAME with value.
  • Macro definition: #define NAME(args) code defines a macro that replaces NAME(args) with code, where args are parameters.

This happens before the compiler runs, during preprocessing.

cpp
#define PI 3.14
#define SQUARE(x) ((x) * (x))
💻

Example

This example shows how to use #define to create a constant and a macro function to calculate the area of a circle and square a number.

cpp
#include <iostream>

#define PI 3.14159
#define SQUARE(x) ((x) * (x))

int main() {
    double radius = 5.0;
    double area = PI * SQUARE(radius);
    std::cout << "Area of circle with radius " << radius << " is " << area << std::endl;
    return 0;
}
Output
Area of circle with radius 5 is 78.53975
⚠️

Common Pitfalls

Common mistakes when using #define include:

  • Not using parentheses around macro parameters and expressions, which can cause unexpected results due to operator precedence.
  • Using #define for constants instead of const or constexpr, which are safer and type-aware.
  • Macros do not respect scopes, so they can cause name clashes or unexpected substitutions.
cpp
#define BAD_SQUARE(x) x * x  // Wrong: missing parentheses

// Correct way:
#define GOOD_SQUARE(x) ((x) * (x))
📊

Quick Reference

UsageDescriptionExample
ConstantDefines a constant value#define MAX 100
Macro with argsDefines a macro function#define MUL(a,b) ((a)*(b))
UndefineRemoves a macro definition#undef MAX
ConditionalDefines macros conditionally#ifdef DEBUG ... #endif

Key Takeaways

#define creates text substitutions before compilation in C++.
Always use parentheses in macros to avoid operator precedence bugs.
Prefer const or constexpr for constants instead of #define.
Macros do not respect scopes and can cause unexpected issues.
Use #undef to remove macro definitions if needed.