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
}
- Introduced in C99 standard
- Improves speed by avoiding function-call overhead
- Compiler may ignore inline request
- Best suited for short, frequently used functions
How Inline Works Internally?
Normally, function calls require:
- Pushing parameters to stack
- Jumping to function address
- Returning back to caller
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
- Functions with loops
- Functions with recursion
- Functions too large in size
- Functions using static variables
- Variadic functions (with ...)
Inline works best for **small mathematical functions, getters, setters**, etc.
Advantages of Inline Functions
- Faster execution (no function call overhead)
- No stack push/pop operations
- Improves optimization for small functions
Disadvantages
- Increases code size (code duplication)
- May lead to slow performance if overused
- Compiler can reject inline request
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
- Inline is type-safe; macros are not
- Inline functions are checked by compiler
- Macros only perform text replacement
Macro Example (Unsafe)
#define SQUARE(x) (x*x)
Inline Example (Safe)
inline int square(int x){ return x*x; }
Real Life Use Cases
- Math shortcut functions (min, max, square)
- Small utility functions
- Performance-critical embedded systems
- Functions used inside loops
Practice Questions
- What is an inline function?
- Difference between inline and macro?
- Why compiler may ignore inline request?
- Write an inline function for cube of a number.
- 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