An inline function is a function that is expanded in line when it is called, rather than invoking the function through the usual function call mechanism. This avoids the overhead of a function call and improves the performance of the program. In C++, we can define a function as inline by using the inline keyword.
Here's an example of an inline function in C++:
inline int add(int x, int y) {
return x + y;
}
int main() {
int a = 5, b = 7;
cout << "The sum of " << a << " and " << b << " is " << add(a, b) << endl;
return 0;
}
In this example, the add() function is defined as inline using the inline keyword. When the add() function is called in the main() function, the compiler expands the function code in place of the function call, resulting in faster execution.
Note that the use of inline keyword is just a request to the compiler, and it is up to the compiler to decide whether to actually expand the function in line or not. Also, inline functions should be short and simple, and should not contain loops or recursive function calls, as they may lead to code bloat and slower execution.
No comments:
Post a Comment
If you have any doubts, please let me know