Course contentsShow
← C
Lesson 370 of 1,2195. FunctionsFree lesson

Macros vs. Inline functions

Macros vs. Inline functions

What you'll learn: How to choose between preprocessor macros and the inline keyword for writing faster, safer code.

In the world of C optimization, "inlining" is the act of injecting a function's code directly into the spot where it is called, rather than jumping back and forth in memory. Historically, programmers used #define macros to achieve this. Modern C offers the inline keyword. While they look similar, they work very differently under the hood.

The Blind Copy-Paste: Macros

A macro is like a "Find and Replace" command. Before your code even compiles, the preprocessor blindly swaps the macro name with your snippet of code.

Macros are powerful but dangerous because they don't understand C logic. They don't check data types, and they can cause "double-evaluation" bugs. For example, if you pass x++ into a macro that uses that variable twice, x will be incremented twice, likely breaking your logic.

The Smart Suggestion: Inline Functions

An inline function is a real function. It follows all the rules of C: it has scope, it checks types, and it evaluates arguments exactly once. By adding the inline keyword, you are giving the compiler a "hint" that it should try to integrate the function body into the caller to save time.

Think of a macro as a rubber stamp (it just smashes the same ink everywhere) and an inline function as a specialized worker who integrates their task directly into the assembly line.

Comparison in Action

See how the macro can fail where the inline function succeeds:

#include <stdio.h>

// The Macro way (Dangerous)
#define SQUARE_MACRO(x) ((x) * (x))

// The Inline way (Safe)
static inline int square_inline(int x) {
    return x * x;
}

int main() {
    int a = 5;
    
    // Works fine
    printf("Inline: %d\n", square_inline(++a)); // a becomes 6, result is 36

    int b = 5;
    // DANGER: Increments b TWICE because the macro expands to ((++b) * (++b))
    printf("Macro: %d\n", SQUARE_MACRO(++b));  // b becomes 7, result is 49!
    
    return 0;
}

Which one should you use?

In modern C, always prefer inline functions. They provide the same performance benefits as macros but include the "safety net" of the compiler’s type-checking and predictable logic. Use macros only when you need to do something a function literally cannot do, like stringifying names or performing complex preprocessor magic.

Key takeaway

Use inline functions for performance and type safety; avoid macros for logic, as they are prone to unexpected side effects.