What is inline keyword in C: Explanation and Example
inline keyword in C suggests to the compiler to replace a function call with the function's code directly, reducing the overhead of calling the function. It helps improve performance by avoiding the usual function call steps but does not guarantee inlining.How It Works
When you call a function in C, the program usually jumps to the function's code, runs it, and then returns back. This jumping takes some time, like walking to another room to get something and then coming back.
The inline keyword tells the compiler, "Instead of jumping, just copy the function's code right here." This is like having the item already in your hand, so you don't need to walk anywhere.
This can make the program faster, especially for small functions that are called many times. But the compiler decides if it actually copies the code or not, based on what makes sense.
Example
This example shows a small function marked as inline. The compiler may replace calls to square with the actual code x * x to speed up the program.
#include <stdio.h> inline int square(int x) { return x * x; } int main() { int num = 5; printf("Square of %d is %d\n", num, square(num)); return 0; }
When to Use
Use inline for small, frequently called functions where the overhead of calling the function is noticeable. Examples include simple math operations, getters, or setters.
It is not useful for large functions because copying big code can increase the program size and hurt performance.
Remember, inline is a suggestion to the compiler, not a command. The compiler may ignore it if it thinks inlining is not beneficial.
Key Points
inlinereduces function call overhead by copying code.- It is best for small, simple functions.
- The compiler decides whether to inline or not.
- Using
inlinecan increase program size if overused. - It helps improve performance but should be used wisely.