Junior — Middle
Can you explain the purpose and use of the inline keyword in programming and why it is used?
sobes.tech AI
Answer from AI
The inline keyword in C/C++ is used to suggest to the compiler to replace a function call with the function's body directly at the call site, to avoid the overhead of a function call (such as address jumping, context saving).
Main reasons for using inline:
- Reducing execution time by eliminating the function call overhead.
- Increasing efficiency for small functions that are called frequently.
However, the compiler is not obliged to inline, it is only a recommendation.
Example:
inline int add(int a, int b) {
return a + b;
}
int main() {
int result = add(2, 3); // the compiler may replace the call with '2 + 3'
}
It is important not to overuse inline for large functions, as this can lead to an increase in binary size (code bloat). Modern compilers often decide on their own which functions to inline based on optimizations.