Skip to content
StudyFame

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

TypeExampleUsed for
Object-like#define MAX_SIZE 100Constants, messages, settings
Function-like#define MAX(a, b) ((a) > (b) ? (a) : (b))Small calculations without a function call
Multi-lineLines 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

  1. COURSE and MAX_MARKS are object-like macros: plain names for a string and a number.
  2. SQUARE(5) expands to ((5) * (5)) = 25.
  3. BAD_SQUARE(2 + 3) expands to 2 + 3 * 2 + 3. Multiplication happens first: 2 + 6 + 3 = 11, not 25.
  4. SQUARE(2 + 3) expands to ((2 + 3) * (2 + 3)) = 25, because every argument has its own brackets.
  5. MAX(7, 12) uses the conditional operator: ((7) > (12) ? (7) : (12)) = 12.
  6. A macro can use another macro: PERCENT uses MAX_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)), so 100 / SQUARE(5) becomes 100 / ((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) becomes printf("score1" " = %d\n", score1). Two strings side by side are joined by the compiler.
  • name##num (token pasting) glues score and 1 into one name, score1.
  • Each line of SWAP ends with \, so the preprocessor treats them as one line.
  • do { ... } while (0) makes the macro behave like one statement, so SWAP(x, y); works safely even inside an if without 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 in do { } while (0).
  • # = make a string; ## = join two tokens.
  • By convention, macro names are written in UPPERCASE.

Common Mistakes Beginners Make

MistakeWhat happensFix
#define SQUARE(x) x * xSQUARE(2+3) gives 11((x) * (x))
#define DOUBLE(x) (x) + (x)10 * DOUBLE(2) gives 22, not 40Bracket the whole body: ((x) + (x))
Passing i++ to a macroThe argument may be evaluated twicePass simple variables or use a function
Space after the macro name#define MAX (a, b) ... is an object macroWrite MAX(a, b)
Forgetting \ on a lineThe macro ends early; strange errors followEnd every line except the last with \

Macros Practice Questions

  1. What is macro expansion?
  2. What is the difference between an object-like and a function-like macro?
  3. What does BAD_SQUARE(1 + 1) give for #define BAD_SQUARE(x) x * x?
  4. What does the # operator do inside a macro?
  5. Why are multi-line macros wrapped in do { } while (0)?
Show answers
  1. Replacing each use of a macro with its definition, done by the preprocessor before compilation.
  2. An object-like macro has no parameters (a named value); a function-like macro takes parameters like a function.
  3. 1 + 1 * 1 + 1 = 3.
  4. It turns the macro argument into a string literal (stringizing).
  5. So the macro acts as a single statement and works correctly with if/else and 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)

  1. Macros are expanded by the:

    A) Compiler   B) Linker   C) Preprocessor   D) Loader

  2. For #define SQ(x) x*x, what is SQ(3+1)?

    A) 16   B) 7   C) 10   D) 8

  3. The ## operator in a macro:

    A) Makes a comment   B) Joins two tokens   C) Makes a string   D) Divides values

  4. Which character continues a macro on the next line?

    A) /   B) ;   C) \   D) #

  5. #define PI 3.14 is a:

    A) Function-like macro   B) Object-like macro   C) Variable   D) Function

Show answers
  1. C: the preprocessor.
  2. B: 3+1*3+1 = 7.
  3. B: it joins two tokens.
  4. C: the backslash.
  5. 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

MacroNamed code, replaced by the preprocessor
Macro expansionText replacement before compilation
Object-likeNo parameters: #define SIZE 10
Function-likeTakes parameters: SQUARE(x)
BracketsAround each parameter and the whole body
# operatorStringizing: argument to string
## operatorToken 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.