CodeBlanks Logo Icon CodeBlanks

Macro functions

  • C course
  • Beginner
  • Lesson 109/116
  • 5 min

Learn to write parameterized macro functions.

Macro functions

A #define directive can also take parameters; this is called a macro function. It is expanded as text at the call site before compilation.

#define SQUARE(x) ((x) * (x))

int r = SQUARE(5);  /* ((5) * (5)) = 25 */

Each parameter should be wrapped in parentheses; otherwise precedence issues arise. For example SQUARE(a+b) expands to ((a+b) * (a+b)). Macro functions are text substitution before compilation; they do not perform type checking; use them carefully.

The importance of parentheses

In macro functions each parameter should be wrapped in parentheses. Otherwise precedence errors occur.

#define BAD(x)  x * x
#define GOOD(x) ((x) * (x))

BAD(2+3)   /* 2+3*2+3 = 11 */
GOOD(2+3)  /* ((2+3) * (2+3)) = 25 */

The BAD macro does not parenthesize its parameters, so it expands to 2+3*2+3; this gives a wrong result. GOOD gives the expected 25 thanks to proper parenthesization. So always use parentheses when writing macros.

Practice Compute square with the SQUARE macro

Define the macro #define SQUARE(x) ((x) * (x)). In main print the value of SQUARE(5) with printf using the %d format.

Starter code

main.c
#include <stdio.h>

// Define the SQUARE(x) macro
int main(void) {
    // Print the value of SQUARE(5) with printf
    return 0;
}

Sample solution

main.c
#define SQUARE(x) ((x) * (x))
printf("%d\n", SQUARE(5));

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main difference between a macro function and a real function?

  • A macro is text substitution before compilation Correct answer
  • A macro is safer
  • A macro has no type checking
  • A macro is slower

Explanation: A macro is not a function; it is text substitution before compilation.

2 Match macro to behavior

Term Meaning
#define PI 3.14 Constant
#define SQUARE(x) Macro function
((x) * (x)) Parenthesized body
#include Includes a header

3 Fill in the blank: macro function body

Question
#define SQUARE(x) ____
Answer
#define SQUARE(x) ((x) * (x))

Explanation: ((x) * (x)) parenthesizes each parameter; expands correctly.

All lessons in Beginner