C++ inline function, parameter passed by value

2.8k views Asked by At

well last time I checked an inline function is a function whose body is substituted directly in every point in the program where the function is called. So when I do this :

#include <iostream>
inline void increment(int n) { n = n + 1; }`
int main() { 
   int n = 0;
   increment(n);
   std::cout << "Result " << n;
}

I should have : Result 1. Instead, I get 0.

So how does an inline function work ?

3

There are 3 answers

2
rafeek On BEST ANSWER

'inline' doesn't replace the text with the function body the way a macro does. It replaces the function call with the EQUIVALENT generated code, so that functionaly it's no different than if it weren't inline.

0
tadman On

This is not a problem with it being inline but with the method signature being wrong:

inline void increment(int& n) {
  ++n;
}

You're asking for a copy, you're getting one. Instead ask for a reference. Don't confuse inline functions with macros, they are not the same. In fact, declaring things inline is usually counter-productive as the compiler will make this call for you depending on your optimization settings.

0
ravi On

There are two things you should consider while inlining.

1) Inline is just a request to compiler rather than command to replace the function call with its body so as to avoid overhead related to function calls.

2) You should always inline the functions which are pretty small like getters/setters. Because inlining large functions OR recursive functions lead to code bloat which defeats the purpose of inlining.

Also inline functions have static linkage.