×

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than the function call. It can enhance performance, particularly for little and frequently mentioned activities.

Syntax Containing Code:

#include <iostream>

inline int square(int x) {

    return x * x;

}

int main() {

    std::cout << "Square of 5: " << square(5) << std::endl;

    return 0;

}

When to use inline functions:

  • Use inline functions for short, frequently used functions (like getters, setters, or utility functions).
  • Inline functions should not be used for large functions, loops, recursion, or complex logic.

Algorithm:

Below is the step-by-step points for the inline function algorithm

  1. Start
  2. Define an inline function with the inline keyword.
  3. The function takes an integer parameter and returns its square.
  4. Call the inline function from main(), passing an integer argument.
  5. The compiler replaces the function call with the actual function definition.
  6. Display the result.
  7. End.

Pseudo code:

Pseudo code for inline function for square function:

BEGIN

    DEFINE INLINE FUNCTION square(x)

        RETURN x * x

    END FUNCTION


    BEGIN MAIN

        DECLARE num ← 5

        DECLARE result ← square(num)

        PRINT "Square of", num, ":", result

    END MAIN

END

Explanation:

  • The definition of the function square(x) is added at the call site without a function call because it is marked as inline.
  • The program initializes an integer num with a value (e.g., 5).
  • The square() function is called, calculating and returning x * x.
  • The result is printed on the console.

Example 1:

Let us take an example using multiple Inline Functions for square, cube and Doubling a number in C++.

#include <iostream>

// Inline function to calculate square

inline int square(int x) {

    return x * x;

}

// Inline function to calculate cube

inline int cube(int x) {

    return x * x * x;

}

// Inline function to double a number

inline int doubleNumber(int x) {

    return x * 2;

}

int main() {

    int num = 4;

    // Calling inline functions

    std::cout << "Square of " << num << " is: " << square(num) << std::endl;

    std::cout << "Cube of " << num << " is: " << cube(num) << std::endl;

    std::cout << "Double of " << num << " is: " << doubleNumber(num) << std::endl;

    return 0;

}

Output:

Square of 4 is: 16

Cube of 4 is: 64

Double of 4 is: 8

Example 2:

Let us take an example to illustrate the Inline function inside a class in C++.

#include <iostream>


class MathOperations {

public:

    // Inline function to calculate square

    inline int square(int x) {

        return x * x;

    }


    // Inline function to calculate cube

    inline int cube(int x) {

        return x * x * x;

    }


    // Inline function to find the maximum of two numbers

    inline int max(int a, int b) {

        return (a > b) ? a : b;

    }

};


int main() {

    MathOperations math;  // Creating an object of the class


    int num1 = 3, num2 = 5; 

    // Calling inline functions

    std::cout << "Square of " << num1 << " is: " << math.square(num1) << std::endl;

    std::cout << "Cube of " << num1 << " is: " << math.cube(num1) << std::endl;

    std::cout << "Maximum of " << num1 << " and " << num2 << " is: " << math.max(num1, num2) << std::endl;

    return 0;

}

Output:

Square of 3 is: 9

Cube of 3 is: 27

Maximum of 3 and 5 is: 5

Advantages of Inline Function:

Several advantages of the inline function in C++ are as follows:

  1. Reduces Function Call Overhead: Since the function code is inserted straight into the calling location, there is no need for a function call or the pushing and popping of registers.
  2. Faster Execution: Inline expansion can lead to faster execution for small routines.
  3. Better Code Optimization: The compiler can optimize inline functions more effectively because it has access to the entire function definition.

Disadvantages of Inline Function:

Several disadvantages of the inline function in C++ are as follows:

  1. Code Duplication: A large inline function, which is called repeatedly, causes more code duplication and a greater binary size.
  2. Compiler Dependency: If a function is too complicated, probably the compiler will ignore the inline keyword, which is just a hint.
  3. Slower Compilation: The compilation time is increased when inline functions are expanded repeatedly.

Conclusion:

In conclusion, C++’s robust inline functions eliminate the overhead of function calls because the function body is a part of the compilation. In general terms, this method maximizes output and minimizes execution time, especially for small, routine tasks. Inline functions should be used sparingly since they can expand the code and increase binary files, particularly when dealing with complex or large routines. Ultimately the decision of inline function usage will be determined by optimization flags and the compiler itself. When used appropriately, inline functions can enhance output considerably without damaging code structure or readability.


Related Topics

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

C++ String Class and its Applications

The String class is available in C++. The character array is represented by the C string. The string class in C++ has a few different attributes. It contains several functions...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.

Backtracking Time Complexity in C++

Introduction to Backtracking Backtracking is an important part of programming languages, and with the help of backtracking, we can do many operations in an advanced data structure. For doing major operations,...

4 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

Similarities between C++ and Java

People who are preparing for software engineering roles must have come across either one of these languages because as all the companies do not accept python for hiring a fresher...

3 minutes read.

Passing a Vector to a function in C++

A pointer is sent to the function when we feed it an array. However, there are two ways to pass a vector: Pass by Value Pass by Reference A copy of a vector...

3 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare...

4 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

Functions in C++ with Types and Examples

A function is a collection of statements that work together to complete a certain goal. It could consist of statements that execute repetitive operations or statements that conduct specialized jobs...

10 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Hospital Management Project in C++

The following capabilities are required to build a hospital management project: These are as follows: hospitals' names, contact information, and lists of doctors and patients. Activities Supported Hospital Data Print Patients' data to...

4 minutes read.