2: Inline Functions in C++
In C++, we can declare a function as inline. This copies the function to the location of the
function call in compile-time and may make the program execution faster.
C++ provides inline functions to reduce the function call overhead.
An inline function is a function that is expanded in line when it is called.
When the inline function is called whole code of the inline function gets inserted or substituted
at the point of the inline function call.
Example 1: C++ Inline Function
#include <iostream>
using namespace std;
inline void displayNum(int num)
{
cout << num << endl;
}
int main() {
// first function call
displayNum(5);
// second function call
displayNum(8);
// third function call
displayNum(666);
return 0;
}
Output
5
8
666
Example 2: C++ Inline Function
#include <iostream>
using namespace std;
inline int cube(int s) { return s * s * s; }
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Output
The cube of 3 is: 27
Example 3: C++ Program to demonstrate inline functions and classes
#include <iostream>
using namespace std;
class operation {
int a, b, add, sub, mul;
float div;
public:
void get();
void sum();
void difference();
void product();
void division();
};
inline void operation ::get()
{
cout << "Enter first value:";
cin >> a;
cout << "Enter second value:";
cin >> b;
}
inline void operation ::sum()
{
add = a + b;
cout << "Addition of two numbers: " << a + b << "\n";
}
inline void operation ::difference()
{
sub = a - b;
cout << "Difference of two numbers: " << a - b << "\n";
}
inline void operation ::product()
{
mul = a * b;
cout << "Product of two numbers: " << a * b << "\n";
}
inline void operation ::division()
{
div = a / b;
cout << "Division of two numbers: " << a / b << "\n";
}
int main()
{
cout << "Program using inline function\n";
operation s;
s.get();
s.sum();
s.difference();
s.product();
s.division();
return 0;
}
Output:
Enter first value: 45
Enter second value: 15
Addition of two numbers: 60
Difference of two numbers: 30
Product of two numbers: 675
Division of two numbers: 3