Trusted answers to developer questions

What is a C++ inline function?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Normally, a function call transfers the control from the calling program to the called function. This process of jumping to the function, saving registers, passing a value to the argument, and returning the value to the calling function takes extra time and memory.

An inline function is a function that is expanded inline when it is invoked, thus saving time. The compiler replaces the function call with the corresponding function code, which reduces the overhead of function calls.

When an inline function is called, the compiler replaces all the calling statements with the function definition at run-time. Every time an inline function is called, the compiler generates a copy of the function’s code, in place, to avoid the function call.

svg viewer

Syntax

inline return_type function_name(parameters)
{
    // function code
}  

Code

#include <iostream>
using namespace std;
inline int max_num(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Greater of ( 40, 50 ) is: " << max_num(40,50) << endl;
cout << "Greater of ( 90, 50 ) is: " << max_num(90,50) << endl;
cout << "Greater of ( -5, 34 ) is: " << max_num(-5,34) << endl;
return 0;
}

Advantages of using inline functions

  • Inline functions speed up your program by avoiding the overhead associated with function calls.
  • Inline functions save the overhead of pushing and popping variables on the stack during function calls.
  • Inline functions save the overhead of the return call from a function.

RELATED TAGS

c++
inline
function
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?