Inline Functions In C++: Fully Explained With Examples

FOTOGRIN / Shutterstock.com

A programmer s journey couldn t be complete without an extensive understanding of functions and what it s possible to do with them. Keeping that in mind, our purpose today is to help you learn in detail all about inline functions in C++.

Why C++? Because it is a robustprogramming languagethat will help translate the logical concepts of functions into practical examples. Inline functions are also found in C, though with a different syntax.

What are Inline Functions?

Historically, programmers developed functions to derive tasks that were done repeatedly over and over again. Improving these mechanisms saves tons of time and resources.

Functions are simple blocks of code that are outside of the regular code path that programmers write. When they are needed, functions can be called using determined keywords.

Taking it a step further, programming languages such asJavascriptand C include their built-in functions. That is also the case with C++. In addition to a large variety of built-in functions, C++ includes the possibility of writing them inline , helping to reduce the function-call overhead. Inline functions are functions that are expanded when called. When correctly used, these functions improve the efficiency of our programs.

But how do inline functions work? Let s talk about it.

How to Inline In C++

A very basic understanding of C++ syntax is all we need to start building programs using inline functions. The syntax fundamentals look like this:

inline return-type function-name(parameters)

{

// function code

}

Once we write it, the structure that defines the functions gets inserted or substituted in line by the compiler. This process can fail for many reasons that you should remember, to avoid compiling errors.

The compiler may ignore our request if the functions contain a loop (for, while, and do-while), static variables, switch, or goto statements, or if the functions are recursive and return a non-void value. Let s have a look at a quick example:

#include 

using namespace std;

inline int cube(int a) { return a * a * a; }
int main()
{
    cout 
Inline functions
A program with a simple inline function.

History-Computer.com

The above example shows how we can use the inline function to do a simple task like calculating the cube of a number. In this case, the function needs an input to work. Once we provide it, the function is ready to make the calculations we need. While this is a simple algorithmic operation, we can create huge combinations.

How to Use Inline Functions Inside Classes

Because C++ is anobject-oriented programming language, we can make programs using objects and constructor classes.

If we define a function inside a class, it s automatically defined as an inline function. This means that we have to take into account all the fundamentals of these functions when programming with classes.

#include 

using namespace std;

class operation {
    int a, b, add, sub, mul;
    float div;
public:
    void get();
    void sum();
};

inline void operation::get() {
    cout > a;
    cout > b;
}

inline void operation::sum() {
    add = a + b;
    cout 
A program illustrating the use of inline functions within classes.

History-Computer.com

This example demonstrates how inline functions are defined inside classes. We ve created a simple calculator using these functions, and the output is quite tidy due to the strings we declared. As you can see, the definition is similar to regular functions, with the only difference being that the function is declared in line.

Practical Examples

We ll be providing two complex examples and explaining them. Pay attention to how the functions are inline in the following code.

#include 
#include 

// Inline function to calculate the area of a circle
inline double calculateCircleArea(double radius) {
    return M_PI * radius * radius;
}

// Inline function to calculate the volume of a cylinder
inline double calculateCylinderVolume(double radius, double height) {
    return M_PI * radius * radius * height;
}

int main() {
    double radius, height;
    std::cout > radius;
    std::cout > height;

    double area = calculateCircleArea(radius);
    double volume = calculateCylinderVolume(radius, height);

    std::cout 

#complex example 1 (image)

By using inline functions the efficiency of the code is increased.

History-Computer.com

We ve created here a program that calculates the area of a circle and the volume of a cylinder. We inline two functions, calculateCircleArea and calculateCylinderVolume , and we call thelibrary to help them perform calculations. In the main function, we ask the user to give us the numbers we ll use for the calculations, just like a normal calculator would. Then we call the inline functions on those inputs and store the results in two variables.

Finally, we print the contents of those variables on the console. This example shows that we can use inline functions for very practical applications and that by implementing them we improve the efficiency of our code. In this particular example, inline functions eliminate the need for function calls. Let s look at the next example.

#include 
#include 

// Inline function to check if a string is palindrome
inline bool isPalindrome(const std::string& str) {
    int left = 0;
    int right = str.length() - 1;

    while (left > word;

    if (isPalindrome(word)) {
        std::cout 
Inline functions are used to check if a word is a palindrome.

History-Computer.com

This is a program that checks whether or not an input word is apalindromeor not. This is also particularly useful for things like managing data sets, so it s another practical example. Here, the inlined function isPalindrome checks if a given string is a palindrome (meaning it reads the same from left to right or right to left).

Basically, it compares the characters at each position iteratively moving the pointers inward until they find a mismatch, meaning the word is not a palindrome, or they get to the middle, meaning the word is a palindrome.

The word variable stores the string that the user inputs and after passing it as an argument through isPalindrome we print the results.

When to Use Inline Functions

After working with the examples, you should now be capable of implementing inline functions. But how do we decide to use them over regular functions?

To know which is the best option, we first have to understand what is going on behind the code we see, and the computation process that leads to each result.

In a regular function, the program calls theCPU, requesting the instructions located in the computer s memory. The functions take the arguments we give them when we make the call and then process them to return some type of argument.

So, the idea here is that there is a physical, electrical, and mechanical background to everything we re doing when we code. Essentially, we re asking electricity to pass through a certain circuit or go to a specific cell in ourhard drive.

This communication between components can take some time, depending on the particularities of the program. If the execution time of the functions is less than the switching time it takes from the caller function to the called function, it can lead to an event called overhead.

In simple words, overhead is bad time management. When the task takes more time than necessary, there s something we need to optimize in our code. Though the problems that arise from overhead aren t always fatal, they tend to trash our code s performance.

That s why we need to use Inline Functions. If we have simple functions, as we saw in the examples, the best practice is always to write them inline. You see now why we told you that inline functions can improve our code s efficiency. On the contrary, a complex function usually takes more time to run and is slower than the overhead process.

Inline Functions Pros and Cons

There are many advantages to inlining , many of which we ve already learned about. The overall performance of our programs can be improved significantly if we take into consideration the following guidelines.

Overhead malfunctions can be troubleshot using inline coding. Also, when called, an inline function can overhead the push/pop variables in the stack. Moreover, we can also avoid return call overhead.

Since inline functions behave differently than regular functions, they also benefit from context-specific optimization carried out by the compiler. While we won t get too much into this point, this means that writing inline functions allows our compiler to better organize and troubleshoot our code.

Now that we know their advantages, we should also know that inline functions are not always the best tool.

Because they duplicate the code at the moment of execution, inline functions can take more space than regular functions. Therefore, they may be harmful for embedded systems where the size code is more important than performance.

This size incrementation also leads to bigger binary executable files and trashing resources in the computer s memory. Trashing usually results in degrading performance and requires regular maintenance from developers.

Inline Functions in C++: Fully Explained With Examples

We ve reached the end of the article, with many new concepts learned along the way. Let s review what we ve learned today.

First, we saw how regular functions and inline functions differ. Then we explained the syntax and use cases of inline functions before moving on to their main advantages and disadvantages.

Your main takeaway from this article should be that inline functions are an extremely useful feature that can help improve our code s performance. Depending on the situation, however, you may want to use regular functions, as they ll take up less space.

Additionally, we focused on the importance of compilers and how we can write our code in ways that reduce the chances of bugs appearing. This efficiency-based mindset will help you immensely along your programming journey.

We recommend you use the formula we provided at the beginning of this article as a reference. You should always check theofficial documentationfor more useful information. Good luck!

Leave a Comment