How does an inline function differ from a preprocessor macro?
To know the difference between macro and inline function ,firstly we should know what exactly they are and when we should use them.
FUNCTIONS:
int Square(int x){
return(x*X);
}
int main()
{
int value = 5;
int result = Square(value);
cout << result << endl;
}
Function calls have overhead associated with it, as after function finishes execution it has to know where it has to return and also need to store the value in stack memory.
For small applications it won't be a problem, but let's take an example of financial applications where thousands of transactions are happening every second, we can't go with function calls.
MACROS:
# define Square(x) x*x;
int main()
{
int value = 5;
int result = Square(value);
cout << result << endl;
}
int result = Square(x*x)
But macros has bugs associated with it.
#define Square(x) x*x
int main() {
int val = 5;
int result = Square(val + 1);
cout << result << endl;
return 0;
}
Here the output is 11 not 36.
INLINE FUNCTIONS:
inline int Square(int x) {
return x * x;
}
int main() {
using namespace std;
int val = 5;
int result = Square(val + 1);
cout << result << endl;
return 0;
}
Output 36
Inline keyword requests the compiler to replace the function call with the body of the function , here the output is correct because it first evaluates the expression and then passed.It reduces the function call overhead as there is no need to store the return address and stack memory is not required for function arguments.
Comparison Between Macros and Inline Functions:
CONCLUSION:
Inline functions are sometimes more useful than macros, as it improves the performance and is safe to use and reduced function call overhead too. It's just a request to the compiler, certain functions won't be inlined like:
which is a good thing, because that is whenever the compiler thinks it's best to do things another way.