Inline Functions in C++

In this tutorials we will understand the concept of inline functions in C++. If you don’t know what functions in c++ are, you can check it Functions in C++ Intro

A function in C++ is a group of program statements with a unique name that perform a specific task. Functions are used to provide modularity to a program.

Inline Functions in C++

Inline Functions in C++ is a very important concept and feature. To understand this let us first understand how a typical function call works-

In a typical scenario , whenever a function is called, the program flow control is shifted to that function till it completes the execution and then returns back to where the function was called. This context switching mechanism many times causes an additional overhead leading to inefficiency. This overhead issue can be resolved by inlining the function (making the function inline).

Inline functions are actual functions, which are copied everywhere during compilation, like preprocessor macro, so the overhead of function calling is reduced.
If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

Remember, inlining a function is only a request to the compiler, not a command. Compiler can ignore the request for inlining.

Compiler may not perform inlining in such circumstances like:

  • If a function contains a loop. (for, while, do-while)
  • If a function contains static variables.
  • If a function is recursive.
  • If a function return type is other than void, and the return statement doesn’t exist in function body.
  • If a function contains switch or goto statement.
Inline Functions in C++ Example Program

Run Online

Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010
Watch it on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *