Inline Functions (C99)

Inline functions were introduced in **C99** to improve performance by reducing **function call overhead**. When a function is declared inline, the compiler may replace the function call with the actual function code.

What Are Inline Functions?

An inline function is a function where the compiler attempts to expand the function body at the point of call, instead of performing a normal function call.

Syntax:

inline return_type function_name(parameters) {
    // code
}

How Inline Works Internally?

Normally, function calls require:

Inline avoids this by directly inserting function code into the calling point.

Important: Inline is a request, not a command. Compiler may ignore inline if the function is too complex.

When Inline Is Not Applied

Inline works best for **small mathematical functions, getters, setters**, etc.

Advantages of Inline Functions

Disadvantages

Example: Simple Inline Function

#include <stdio.h>

inline int square(int n){
    return n * n;
}

int main(){
    printf("Square: %d", square(6));
    return 0;
}

Example: Inline Function for Addition

#include <stdio.h>

inline int add(int a, int b){
    return a + b;
}

int main(){
    printf("Sum: %d", add(10, 20));
    return 0;
}

Inline Function vs Macro

Macro Example (Unsafe)

#define SQUARE(x) (x*x)

Inline Example (Safe)

inline int square(int x){ return x*x; }

Real Life Use Cases

Practice Questions

  1. What is an inline function?
  2. Difference between inline and macro?
  3. Why compiler may ignore inline request?
  4. Write an inline function for cube of a number.
  5. Where are inline functions best used?

Practice Task

Write program using 3 inline functions: 1️⃣ Add two numbers 2️⃣ Return maximum number 3️⃣ Return factorial (non-inline) and compare performance