This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, February 16, 2023

What is inline function? Using inline function, write a program to add two integers and returns sum.

 An inline function is a function that is expanded in line at the point where it is called. It is a function that is defined with the 'inline' keyword, which indicates to the compiler that the function should be expanded inline, rather than called as a separate function. The inline function can provide faster execution than a regular function call because there is no function call overhead.

Here is an example program that uses an inline function to add integers and return the sum:

#include <iostream>
using namespace std;

inline int add(int a, int b) {
    return a + b;
}

int main() {
    int x = 30;
    int y = 40;
    int result = add(x, y);
    cout << "The sum of " << x << " and " << y << " is " << result << endl;
    return 0;
}

In the above program the "add()" function is defined with the "inline" keyword, which tells the compiler to expand the function in line wherever it is called. The function takes two integer parameters, adds the together, and returns the sum.

In the "main()" function, we declare two integer variables 'x' and 'y' and initialize them to 30 and 40, respectively. We then call the 'add()' function with 'x' and 'y' as arguments and store the result in 'result' variable. Finally, we output the result to the console using 'cout'.

Because the 'add()' function is defined as an inline function, the compiler expands the function in line wherever it is called, resulting in faster execution. This can be particularly useful for small, frequently used functions, where the overhead of a regular function call can have a noticeable impact on performance.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget