← Back to C Course | Chapter 14: Additional Topics | Lesson 5 of 9

C Inline Functions

What is an Inline Function?

Marking a function inline is a request for the compiler to substitute the function's actual code directly at each call site instead of generating a normal function call, which can eliminate call overhead for small, frequently-called functions like simple getters or one-line calculations.

Example: What is an Inline Function?

c
#include <stdio.h>
inline int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(5));
	return 0;
}

The inline Keyword

To declare an inline function, write the inline keyword before the return type in the function definition; pairing it with static (as static inline) is the conventional way to define small inline helpers in a header without triggering multiple-definition linker errors when that header is included in several files.

Example: The inline Keyword

c
#include <stdio.h>
static inline int cube(int n) {
	return n * n * n;
}
int main() {
	printf("%d", cube(3));
	return 0;
}

Inline Functions vs. Macros

Unlike a preprocessor #define macro, which does pure blind text substitution with no awareness of types, an inline function is a real function that the compiler type-checks normally, respects scoping rules for, and can still be stepped through with a debugger — trading a little of a macro's raw flexibility for genuine safety.

Example: Inline Functions vs. Macros

c
#include <stdio.h>
static inline int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(1 + 2));
	return 0;
}

Where to Define Inline Functions

Because the compiler needs to see a function's full body at every point it might be inlined, inline functions intended for use across multiple .c files are typically defined directly inside a shared header, rather than split into a separate declaration-only header plus a .c implementation file.

Example: Where to Define Inline Functions

c
#include <stdio.h>
static inline int add(int a, int b) {
	return a + b;
}
int main() {
	printf("%d", add(2, 3));
	return 0;
}

Compiler Optimizations

The inline keyword is only ever a hint to the compiler, not a guaranteed instruction — the compiler is free to inline a function that isn't marked inline if it judges that beneficial, and equally free to ignore the inline hint on a function it decides is too large or too complex (such as one containing a loop or recursion) to safely inline.

Example: Compiler Optimizations

c
#include <stdio.h>
inline int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(4));
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.