Site Tools


wiki:c-function-macro

Table of Contents

C Function macro

Function macro is a preprocessor macro that looks and behaves like a function call. Arguments must be wrapped in parentheses to preserve precedence during substitution. Multi-statement function macros should use do { ... } while (0) to ensure proper scoping and require semicolon syntax.

Always parenthesize macro arguments to avoid operator precedence bugs.

Example

This example demonstrates function macros with proper argument protection and multi-statement wrapping.

// compile: gcc -o funcmacro funcmacro.c
// run: ./funcmacro
// description: function macros look like functions but substitute inline
 
#include <stdio.h>
 
#define MAX(a, b) ((a) > (b) ? (a) : (b))
 
#define PRINT_PAIR(x, y) do { \
    printf("Values: %d, %d\n", (x), (y)); \
    printf("Max: %d\n", MAX((x), (y))); \
} while (0)
 
int main() {
    int x = 5, y = 3;
    PRINT_PAIR(x, y);
 
    int z = MAX(2 + 3, 4 + 1);  // correct: (2+3) and (4+1), not 2+3 and 4+1
    printf("Result: %d\n", z);
 
    return 0;
}
wiki/c-function-macro.md · Last modified: by 127.0.0.1