Inline functions

Calling a function takes a certain amount of time. The return address is placed on the stack. The parameters are also placed on the stack. The function is started. The parameters are enabled again after the function has ended and the program jumps back to the starting point. Even if this all sounds tedious, calling a function only takes a small part of the runtime of a program and is usually of no consequence.

In time-critical applications, however, calling a function can already take too much time. To avoid this, the inline attribute can be placed in front of a function. In this case, the compiler will not call the instructions as a function, but instead copy the function content in place of the function call. If the compiler determines that such a replacement does not bring any runtime advantages, it is free to compile the inline function so that it is called like any other function.

#include <iostream>
using namespace std;

inline float avg (float a, float b) {
	return a + b / 2;
}

int main () {
	cout << "Average: " << avg(2, 7) << endl;
	return 0;
}

Output

Average: 5.5

Code Explanation

This simple C++ program defines an inline function avg to calculate the average of two floating-point numbers a and b. The function returns the sum of the two numbers divided by 2.

In the main function, the avg function is called with the arguments 2 and 7 and the returned result is printed to the console using the cout statement.

It’s worth noting that the order of operations is important in this code. The addition of a and b is performed before the division by 2