0
0
CHow-ToBeginner · 3 min read

How to Create Macro in C: Syntax and Examples

In C, you create a macro using the #define directive followed by the macro name and its replacement value or code. Macros are simple text substitutions done by the preprocessor before compilation.
📐

Syntax

The basic syntax to create a macro in C is:

#define MACRO_NAME replacement_text

Here:

  • #define tells the compiler to create a macro.
  • MACRO_NAME is the name you choose for the macro (usually uppercase by convention).
  • replacement_text is the value or code that replaces the macro wherever it appears.
c
#define PI 3.14
#define MAX(a,b) ((a) > (b) ? (a) : (b))
💻

Example

This example shows how to define a simple macro and a macro with parameters, then use them in a program.

c
#include <stdio.h>

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

int main() {
    double radius = 5.0;
    double area = PI * SQUARE(radius);
    printf("Area of circle with radius %.2f is %.2f\n", radius, area);
    return 0;
}
Output
Area of circle with radius 5.00 is 78.54
⚠️

Common Pitfalls

Common mistakes when creating macros include:

  • Not using parentheses around macro parameters and the entire replacement expression, which can cause unexpected results due to operator precedence.
  • Macros do not perform type checking, so misuse can cause bugs.
  • Macros can make debugging harder because they are replaced before compilation.
c
#define BAD_SQUARE(x) x * x  // Wrong: missing parentheses
#define GOOD_SQUARE(x) ((x) * (x))  // Correct: safe with parentheses
📊

Quick Reference

Macro TypeSyntax ExampleDescription
Object-like#define PI 3.14Replaces name with a value or text
Function-like#define MAX(a,b) ((a) > (b) ? (a) : (b))Replaces with code using parameters
Conditional#ifdef DEBUG ... #endifCompiles code only if macro is defined
Undefine#undef MACRO_NAMERemoves a macro definition

Key Takeaways

Use #define to create macros that replace text before compilation.
Always use parentheses around macro parameters and the entire expression to avoid errors.
Macros do not check types and can make debugging harder.
Function-like macros can take parameters and act like inline functions.
Use #undef to remove a macro if needed.