C Inline Functions
In this page:
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?
#include <stdio.h>
inline int square(int n) {
return n * n;
}
int main() {
printf("%d", square(5));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
static inline int cube(int n) {
return n * n * n;
}
int main() {
printf("%d", cube(3));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
static inline int square(int n) {
return n * n;
}
int main() {
printf("%d", square(1 + 2));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
static inline int add(int a, int b) {
return a + b;
}
int main() {
printf("%d", add(2, 3));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
inline int square(int n) {
return n * n;
}
int main() {
printf("%d", square(4));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: