How to Use #define in C: Simple Guide with Examples
In C,
#define is a preprocessor directive used to create symbolic constants or macros. It replaces all occurrences of a name with a value or code snippet before compilation. For example, #define PI 3.14 replaces every PI with 3.14 in your code.Syntax
The #define directive has two main forms:
- Constant definition:
#define NAME valuereplacesNAMEwithvalue. - Macro definition:
#define NAME(parameters) codereplacesNAME(args)withcodeusing those arguments.
This happens before the program compiles, so no memory is used for these replacements.
c
#define NAME value #define SQUARE(x) ((x) * (x))
Example
This example shows how to use #define to create a constant and a macro function. It calculates the area of a circle using the constant PI and the macro SQUARE.
c
#include <stdio.h> #define PI 3.14 #define SQUARE(x) ((x) * (x)) int main() { float radius = 5.0; float area = PI * SQUARE(radius); printf("Area of circle with radius %.1f is %.2f\n", radius, area); return 0; }
Output
Area of circle with radius 5.0 is 78.50
Common Pitfalls
Common mistakes when using #define include:
- Not using parentheses in macros, which can cause wrong calculations.
- Defining macros that evaluate arguments multiple times, causing side effects.
- Using
#definefor constants instead ofconstvariables, which can be safer.
Always wrap macro parameters and the entire macro body in parentheses to avoid errors.
c
#define BAD_SQUARE(x) x * x // Wrong: no parentheses #define GOOD_SQUARE(x) ((x) * (x)) // Correct: safe macro // Example usage: // BAD_SQUARE(1 + 2) expands to 1 + 2 * 1 + 2 = 1 + 2 + 2 = 5 (wrong) // GOOD_SQUARE(1 + 2) expands to ((1 + 2) * (1 + 2)) = 9 (correct)
Quick Reference
| Usage | Description | Example |
|---|---|---|
| Constant | Defines a constant value | #define MAX 100 |
| Simple Macro | Defines a macro without parameters | #define PI 3.14 |
| Function-like Macro | Defines a macro with parameters | #define SQUARE(x) ((x) * (x)) |
| Multi-line Macro | Defines a macro spanning multiple lines | #define PRINT(x) \ printf("%d\n", x) |
Key Takeaways
Use
#define to create constants or macros that replace code before compilation.Always wrap macro parameters and the entire macro body in parentheses to avoid errors.
Macros do not use memory but can cause unexpected behavior if not carefully written.
Prefer
const variables for constants when possible for better type safety.Multi-line macros use a backslash (\) at the end of each line except the last.