Course contentsShow
← C
Lesson 772 of 1,21911. The Preprocessor and BuildFree lesson

Defining function-like macros

Defining function-like macros

What you'll learn: How to create preprocessor shortcuts that look like functions but work by simple text replacement.

The Smart Search-and-Replace

In previous lessons, we used macros to give names to numbers, like #define PI 3.14. A function-like macro takes this a step further. It allows you to define a template with placeholders. When the preprocessor sees your macro in the code, it doesn't "call" it like a function; it physically swaps the template into your code and plugs in your values.

Think of it like a "Find and Replace" feature in a text editor. If you have a template for a formal letter that says Dear [NAME], and you tell your editor that [NAME] is "Alice," the editor simply swaps the text. The computer doesn't "think" about the name; it just moves the characters around before the compiler even starts its job.

Defining the Macro

To create a function-like macro, you use #define followed by the name and a list of arguments in parentheses. Crucially, there must be no space between the macro name and the opening parenthesis.

#include <stdio.h>

// This macro calculates the square of a number
#define SQUARE(x) ((x) * (x))

int main() {
    int side = 5;
    
    // The preprocessor turns the next line into: 
    // printf("Area: %d\n", ((side) * (side)));
    printf("Area: %d\n", SQUARE(side));

    return 0;
}

Why all the parentheses?

You might notice the heavy use of parentheses in ((x) * (x)). Because macros are just text substitution, they can be "tricky." If you defined it as #define SQUARE(x) x * x and then wrote SQUARE(2 + 2), the preprocessor would give you 2 + 2 * 2 + 2. Due to the order of operations (multiplication before addition), you would get 8 instead of the expected 16.

By wrapping the arguments and the entire expression in parentheses, you ensure the math stays safe regardless of what the user passes in.

When to use them

Function-like macros are incredibly fast because they eliminate the "overhead" of a function call. There is no jumping around in memory; the code is right there where you need it. They are best used for very short, one-line logic like finding the maximum of two numbers or converting units.

Key takeaway

Function-like macros are preprocessor templates that perform a "search-and-replace" on your code before compilation, providing speed but requiring careful use of parentheses.