Skip to main content

Functional Macros in C

A function-like macro (also called a parameterised macro) accepts arguments and expands them inline — like a function, but done at the preprocessor stage before compilation. They are faster than function calls because there is no function call overhead.

Syntax

#define MACRO_NAME(param1, param2) (expression)
Always wrap the entire expression and each parameter in parentheses to avoid operator precedence bugs.

Examples

Square of a number:
#define SQUARE(x)  ((x) * (x))
Maximum of two numbers:
#define MAX(a, b)  ((a) > (b) ? (a) : (b))
Minimum of two numbers:
#define MIN(a, b)  ((a) < (b) ? (a) : (b))
Absolute value:
#define ABS(x)     ((x) < 0 ? -(x) : (x))

Complete Program

#include <stdio.h>

#define SQUARE(x)   ((x) * (x))
#define MAX(a, b)   ((a) > (b) ? (a) : (b))
#define CUBE(x)     ((x) * (x) * (x))

int main() {
    int num = 5;

    printf("Square of %d  = %d\n", num, SQUARE(num));
    printf("Cube   of %d  = %d\n", num, CUBE(num));
    printf("Max(3, 7)     = %d\n", MAX(3, 7));

    return 0;
}
Output:
Square of 5  = 25
Cube   of 5  = 125
Max(3, 7)    = 7

Why Parentheses Matter

Without parentheses around parameters, expressions involving operators can produce wrong results:
#define BAD_SQUARE(x)  x * x
// BAD_SQUARE(2 + 3) expands to: 2 + 3 * 2 + 3 = 11 (wrong!)

#define GOOD_SQUARE(x) ((x) * (x))
// GOOD_SQUARE(2 + 3) expands to: ((2+3) * (2+3)) = 25 (correct)
Always parenthesise both the parameters and the full expression.

Macros vs Functions

Functional MacroFunction
Processed byPreprocessorCompiler
Type checkingNoneYes
SpeedFaster — inlinedSlight call overhead
DebuggingHarderEasier
Code sizeLargerSmaller
Side effectsPossibleNone
Use macros for short, frequently-called operations. Prefer inline functions in C99+ for type safety.