×

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

gmtime() function in C/C++

C++ language is used to make high-performance applications that can work efficiently. It is one of the world's most popular languages. It is an object-oriented and high-level programming language, which...

4 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Desired Capabilities in Selenium Web Driver in C++

A class called Desired Capabilities is used to specify a set of fundamental requirements, such as browser, operating system, and version combinations.to carry out automated testing of a web application...

7 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

Hierarchical Inheritance

C++ Hierarchical Inheritance Hierarchical inheritance inherits the property of one base class in more than one derived class.   C++ Hierarchical Inheritance Example #include <iostream>   using namespace std;   class Person {       char gender[10];       int age;   public:       void getPerson()       {           cout << "Age: "; cin >> age;           cout << "Gender: "; cin >> gender;       }       void dispPerson()       {           cout << "Age: " << age << endl;           cout << "Gender: " << gender << endl;       }   };   class Employee : public Person {       float salary;   public:       void getEmployee()       {           Person::getPerson();           cout << "Salary: Rs."; cin >> salary;       }       void dispEmployee()       {           Person::dispPerson();           cout << "Salary: Rs." << salary << endl;       }   };   class Student : public Person {       char level[20];   public:       void getStudent()       {           Person::getPerson();           cout << "Class: "; cin >> level;       }       void dispStudent()       {           Person::dispPerson();           cout << "Level: " << level << endl;       }   };   int main()   {       Person per;       Employee emp;       Student stu;       cout << "Student data" << endl;       cout << "Enter data" << endl;       stu.getStudent();       cout << endl << "Displaying data" << endl;       stu.dispPerson();       cout << endl << "Staff Data" << endl;       cout << "Enter data" << endl;       emp.getEmployee();       cout << endl << "Displaying data" << endl;       emp.dispPerson();   } Output: Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age:...

1 minute read.

Storage Classes in C

Storage Classes in C Storage Classes are used to define the variable and function property. These functionalities include basically the scope, accessibility, and lifetime that help us detect the existence of...

4 minutes read.

How to Reverse a String in C++ using While Loop

A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the condition no longer...

6 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.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.