Inline_vs_macro

Different between inline and macro (in C++)

What is exactly a function?

For a function example:


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 them. After the function finished executing it needs to know where to return to, so it stores the return address on th stack before calling the function. For small applications this might not be a problem. However, say, a financial application, where thousands of transactions are happening every second, a function call might be too expensive.

What is macros?

define Square(x) x*x

int main(){
    int val = 5;
    int result = Square(val + 1);
    cout << result <<endl;
}
#define Square(x) x*x
int main()
{
    int val = 5;
    int result = Square(val + 1);
    cout << result << endl;
}

What is inline functions?

Same example as above:

inline int Square(int x)
{
    return x * x;
}

int main()
{
    int val = 5;
    int result = Square(val + 1);
    cout << result << endl;
}

In a word, the inline keyword requests that a function is called directly by its body instead of the function call.

Inline functions reduce tthe function call overhead as there is no need to store a return address or arguments to the stack.

Nowadays, the compilers are clever enough to judge whether a function should be inlined, but it’s still a good habbit to use static inline function definition.

Comparison between Macros and Inline Functions

  1. The real mechanisms behind the Macros -> text substitution. Inline Function -> duplicate the logic of a function.
  2. Macros are sometimes not safe due to the text substitution.
  3. Macros cannot be assigned to function pointers but inline functions can.
  4. Macros are only suitable for small pieces, i.e., not suitable for many lines of codes.
  5. In C++, macros cannot be used by member functions, while Inline Functions can.
  6. Macros (#define) cannot be debugged.

Conclusion

Inline functions are useful in more scenarios than Macros. Inline actually will make a request to the compiler, and some certain functions cannot be inlined:


Here are some related official docs:

https://gcc.gnu.org/onlinedocs/gcc/Inline.html

https://en.wikipedia.org/wiki/Inline_function

https://www.drdobbs.com/the-new-c-inline-functions/184401540