Home > Article > Backend Development > The difference between C++ inline functions and function pointers
Inline functions are directly expanded without calling, while function pointers store variables pointing to function addresses, allowing indirect function calls.
C The difference between inline functions and function pointers
What is an inline function?
Inline functions are functions that the compiler expands directly at compile time. This means that a call to an inline function does not result in an actual function call, but rather the function code is inserted directly into the location where it is called.
Syntax:
inline 返回值类型 函数名(参数列表) { // 函数体 }
Advantages:
What is a function pointer?
A function pointer is a variable that stores the address of a function. It allows us to call functions in an indirect way.Syntax:
类型 (*函数名)(参数列表);The type represents the return value type of the function pointer, and the parameter list represents the formal parameter type of the function pointer.
Advantages:
Practical case
Inline function:
Consider the following for calculating Fibonacci numbers Inline functions:inline int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci(n - 1) + fibonacci(n - 2); } }
Function pointers:
Consider the following code that uses function pointers to calculate Fibonacci numbers:int (*fib_ptr)(int); int fibonacci_using_ptr(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fib_ptr(n - 1) + fib_ptr(n - 2); } } int main() { fib_ptr = fibonacci; cout << fibonacci_using_ptr(10) << endl; // 输出:55 return 0; }In this example , the function pointer
fib_ptr is assigned to the inline function
fibonacci, which is then used to call the function indirectly.
The above is the detailed content of The difference between C++ inline functions and function pointers. For more information, please follow other related articles on the PHP Chinese website!