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 valuereplaces all occurrences ofNAMEwithvalue. - Macro definition:
#define NAME(args) codedefines a macro that replacesNAME(args)withcode, whereargsare 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
#definefor constants instead ofconstorconstexpr, 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
| Usage | Description | Example |
|---|---|---|
| Constant | Defines a constant value | #define MAX 100 |
| Macro with args | Defines a macro function | #define MUL(a,b) ((a)*(b)) |
| Undefine | Removes a macro definition | #undef MAX |
| Conditional | Defines 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.