how to use inline function
时间: 2024-03-07 09:50:18 浏览: 65
To use an inline function in C++, you need to define the function with the inline keyword before the function definition. Inline functions are functions that are expanded in place where they are called, instead of being called as a separate function. This can lead to faster code execution, as the overhead of calling a function is eliminated.
Here's an example of how to define and use an inline function:
```c++
#include <iostream>
// define an inline function
inline int add(int x, int y) {
return x + y;
}
int main() {
int a = 5, b = 10;
int sum = add(a, b); // call the inline function
std::cout << "The sum of " << a << " and " << b << " is " << sum << std::endl;
return 0;
}
```
In this example, the `add` function is defined as an inline function using the `inline` keyword before the function definition. The function takes two integer arguments and returns their sum.
The `add` function is then called in the `main` function to add the values of `a` and `b`. Since the `add` function is defined as inline, the function call is expanded in place where it is called, instead of being called as a separate function.
I hope this helps answer your question.
阅读全文