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

Macros vs inline functions

Macros vs inline functions

What you'll learn: How to decide between the raw power of text-replacement macros and the type-safe precision of inline functions.

The Copy-Paste Problem

In previous lessons, we saw that macros with arguments look like functions but act like "search and replace" tools. If you define #define SQUARE(x) (x * x), the preprocessor literally rewrites your code before the compiler even sees it.

Think of a macro like a stamp. It doesn't care what it's stamping; it just slams the pattern onto the page. If you pass it something weird—like a variable with a side effect (SQUARE(++i))—the stamp repeats that side effect twice, often breaking your logic.

The Modern Alternative: inline

C provides the inline keyword as a smarter alternative. An inline function is a real function: it has parameter types, a return type, and its own scope. However, it suggests to the compiler: "Instead of jumping to this function's location in memory, just grab its logic and bake it directly into the calling code."

It’s like a template rather than a stamp. The compiler checks the data types first to ensure everything is safe, then optimizes the performance just like a macro would.

Head-to-Head Comparison

Look at how these two approaches handle the same task:

#include <stdio.h>

// The Macro: Dangerous but flexible (works for any type)
#define MAX_MACRO(a, b) ((a) > (b) ? (a) : (b))

// The Inline Function: Safe and predictable
static inline int max_inline(int a, int b) {
    return (a > b) ? a : b;
}

int main() {
    int x = 5, y = 10;

    // Macro works, but lacks type checking
    int res1 = MAX_MACRO(x, y);

    // Inline function works and ensures 'a' and 'b' are actually integers
    int res2 = max_inline(x, y);

    return 0;
}

Which should you use?

In modern C, inline functions are usually the winner. They provide "type safety," meaning the compiler will warn you if you try to pass a string into a math function. They also behave predictably with increments (like i++).

Use macros only when you need "generic" behavior (logic that works on int, float, and double simultaneously) or when you need to perform special preprocessor tricks that a regular function simply cannot do.

Key takeaway

Use inline functions for type safety and debugging; use macros only when you need code that works across multiple data types.