Macros in C
A macro is a name that the preprocessor replaces with some text before compilation. You have already used one: #define PI 3.14159. Macros can also take arguments, like SQUARE(x), and look almost like functions.
In this lesson you will learn the two kinds of macros, why you must put brackets everywhere, how to write multi-line macros, and two special operators: # (turn into a string) and ## (join tokens).
What You Will Learn
- What a macro is and how macro expansion works.
- Object-like macros vs function-like macros.
- Why brackets are needed around arguments and the whole macro.
- How to write a macro over several lines.
- The stringizing operator
#and the token-pasting operator##. - The mistakes that make macros give wrong answers.
Macros in C Explained
Exam definition: A macro is a fragment of code that is given a name with the #define directive. Before compilation, the preprocessor replaces every use of the name with its definition; this is called macro expansion (or macro substitution). An object-like macro has no parameters (#define SIZE 10); a function-like macro takes parameters (#define SQUARE(x) ((x) * (x))).
Memory trick: A macro is find-and-replace in a text editor. The preprocessor doesn't calculate anything; it just copies text. So always ask: "What does the code look like after the copy?" That one question explains every macro bug.
Types of macros
| Type | Example | Used for |
|---|---|---|
| Object-like | #define MAX_SIZE 100 | Constants, messages, settings |
| Function-like | #define MAX(a, b) ((a) > (b) ? (a) : (b)) | Small calculations without a function call |
| Multi-line | Lines joined with \ | Several statements under one name |
| Predefined | __LINE__, __FILE__ | Built-in information from the compiler |
Syntax of a Macro
#define NAME replacement_text /* object-like */
#define NAME(param1, param2) replacement_text /* function-like */
#define LONG_MACRO(x) \
do { \
statement1; \
statement2; \
} while (0) /* multi-line */
#define STR(x) #x /* # turns the argument into "text" */
#define JOIN(a, b) a##b /* ## glues two tokens into one */
There must be no space between the macro name and ( in a function-like macro.
Example 1: Object-like and Function-like Macros
#include <stdio.h>
#define COURSE "C Programming"
#define MAX_MARKS 100
#define BAD_SQUARE(x) x * x
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define PERCENT(m) ((m) * 100.0 / MAX_MARKS)
int main(void)
{
printf("Course: %s\n", COURSE);
printf("SQUARE(5) = %d\n", SQUARE(5));
printf("BAD_SQUARE(2+3) = %d\n", BAD_SQUARE(2 + 3));
printf("SQUARE(2+3) = %d\n", SQUARE(2 + 3));
printf("MAX(7, 12) = %d\n", MAX(7, 12));
printf("PERCENT(87) = %.1f%%\n", PERCENT(87));
return 0;
}
Output
Course: C Programming SQUARE(5) = 25 BAD_SQUARE(2+3) = 11 SQUARE(2+3) = 25 MAX(7, 12) = 12 PERCENT(87) = 87.0%
Code Explanation
COURSEandMAX_MARKSare object-like macros: plain names for a string and a number.SQUARE(5)expands to((5) * (5))= 25.BAD_SQUARE(2 + 3)expands to2 + 3 * 2 + 3. Multiplication happens first: 2 + 6 + 3 = 11, not 25.SQUARE(2 + 3)expands to((2 + 3) * (2 + 3))= 25, because every argument has its own brackets.MAX(7, 12)uses the conditional operator:((7) > (12) ? (7) : (12))= 12.- A macro can use another macro:
PERCENTusesMAX_MARKS.%%prints a percent sign.
How Macro Expansion Works
The preprocessor replaces the macro call with the macro body, putting the given text in place of each parameter:
Definition : #define SQUARE(x) ((x) * (x))
Call : SQUARE(2 + 3)
Step 1 : x = "2 + 3" (the TEXT, not the value 5)
Step 2 : ((x) * (x)) -> ((2 + 3) * (2 + 3))
Compiler : sees ((2 + 3) * (2 + 3)) and calculates 25
Two bracket rules keep macros safe:
- Put each parameter in brackets:
(x). - Put the whole body in brackets:
((x) * (x)), so100 / SQUARE(5)becomes100 / ((5) * (5))= 4, not 100.
Example 2: Multi-line Macros, # and ##
#include <stdio.h>
#define PRINT_INT(var) printf(#var " = %d\n", var)
#define MAKE_VAR(name, num) name##num
#define SWAP(a, b) \
do { \
int t_ = (a); \
(a) = (b); \
(b) = t_; \
} while (0)
int main(void)
{
int MAKE_VAR(score, 1) = 40; /* becomes: int score1 = 40; */
int MAKE_VAR(score, 2) = 55; /* becomes: int score2 = 55; */
PRINT_INT(score1);
PRINT_INT(score2);
PRINT_INT(score1 + score2);
SWAP(score1, score2);
printf("After SWAP:\n");
PRINT_INT(score1);
PRINT_INT(score2);
return 0;
}
Output
score1 = 40 score2 = 55 score1 + score2 = 95 After SWAP: score1 = 55 score2 = 40
- #var (stringizing) turns the argument into a string:
PRINT_INT(score1)becomesprintf("score1" " = %d\n", score1). Two strings side by side are joined by the compiler. - name##num (token pasting) glues
scoreand1into one name,score1. - Each line of
SWAPends with\, so the preprocessor treats them as one line. do { ... } while (0)makes the macro behave like one statement, soSWAP(x, y);works safely even inside anifwithout braces.
Important Points to Remember
- A macro is text replacement; no calculation or type checking happens during expansion.
- Bracket every parameter and the whole body of a function-like macro.
- No space between the macro name and
(. - End each line of a multi-line macro with
\; wrap statements indo { } while (0). #= make a string;##= join two tokens.- By convention, macro names are written in UPPERCASE.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
#define SQUARE(x) x * x | SQUARE(2+3) gives 11 | ((x) * (x)) |
#define DOUBLE(x) (x) + (x) | 10 * DOUBLE(2) gives 22, not 40 | Bracket the whole body: ((x) + (x)) |
Passing i++ to a macro | The argument may be evaluated twice | Pass simple variables or use a function |
| Space after the macro name | #define MAX (a, b) ... is an object macro | Write MAX(a, b) |
Forgetting \ on a line | The macro ends early; strange errors follow | End every line except the last with \ |
Macros Practice Questions
- What is macro expansion?
- What is the difference between an object-like and a function-like macro?
- What does
BAD_SQUARE(1 + 1)give for#define BAD_SQUARE(x) x * x? - What does the
#operator do inside a macro? - Why are multi-line macros wrapped in
do { } while (0)?
Show answers
- Replacing each use of a macro with its definition, done by the preprocessor before compilation.
- An object-like macro has no parameters (a named value); a function-like macro takes parameters like a function.
1 + 1 * 1 + 1= 3.- It turns the macro argument into a string literal (stringizing).
- So the macro acts as a single statement and works correctly with
if/elseand a semicolon after it.
Coding Exercise
Write macros CUBE(x), MIN(a, b), IS_EVEN(n) and SHOW(expr), where SHOW prints the expression text and its value. Use them to print CUBE(1+2), MIN(8, 3) and IS_EVEN(14).
Show solution
#include <stdio.h>
#define CUBE(x) ((x) * (x) * (x))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define IS_EVEN(n) ((n) % 2 == 0)
#define SHOW(expr) printf(#expr " = %d\n", expr)
int main(void)
{
SHOW(CUBE(1 + 2));
SHOW(MIN(8, 3));
SHOW(IS_EVEN(14));
return 0;
}
CUBE(1 + 2) = 27 MIN(8, 3) = 3 IS_EVEN(14) = 1
#expr shows the argument exactly as written, before the inner macro is expanded.
Quick Quiz: Macros in C (MCQ)
-
Macros are expanded by the:
A) Compiler B) Linker C) Preprocessor D) Loader
-
For
#define SQ(x) x*x, what isSQ(3+1)?A) 16 B) 7 C) 10 D) 8
-
The
##operator in a macro:A) Makes a comment B) Joins two tokens C) Makes a string D) Divides values
-
Which character continues a macro on the next line?
A)
/B);C)\D)# -
#define PI 3.14is a:A) Function-like macro B) Object-like macro C) Variable D) Function
Show answers
- C: the preprocessor.
- B:
3+1*3+1= 7. - B: it joins two tokens.
- C: the backslash.
- B: an object-like macro.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Macro | Named code, replaced by the preprocessor |
|---|---|
| Macro expansion | Text replacement before compilation |
| Object-like | No parameters: #define SIZE 10 |
| Function-like | Takes parameters: SQUARE(x) |
| Brackets | Around each parameter and the whole body |
| # operator | Stringizing: argument to string |
| ## operator | Token pasting: joins tokens |
Frequently asked questions
- What is a macro in C?
- A name defined with #define that the preprocessor replaces with its text everywhere before compilation.
- Why does SQUARE(2+3) give 11 without brackets?
- It expands to 2 + 3 * 2 + 3; multiplication happens first, so the result is 11.
- What are the # and ## operators?
- # turns an argument into a string; ## joins two tokens into one.
Remember
- Macro = find and replace; picture the code after expansion.
- Brackets, brackets, brackets.
Next Topic
Next lesson: Macro vs Function in C. You will compare macros with functions: speed, type safety, debugging and side effects.