0

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 ?

iman
  • 145
  • 1
  • 4
  • 11
  • [When should I write the keyword 'inline' for a function/method?](http://stackoverflow.com/a/1759575/701092) – David G Nov 17 '14 at 17:55
  • 1
    A function's logical behaviour is identical whether it is inline or not. – Neil Kirk Nov 17 '14 at 17:56
  • Pass by reference. You increment a *copy* of the parameter, and the copy disappears after the execution leaves your function. – Thomas Matthews Nov 17 '14 at 18:05
  • I know that I'm using a copy. I do it in purpose. I was trying to see if I used an inline function, the call will be directly substituted by n = n + 1. – iman Nov 17 '14 at 18:15
  • @iman: It will, but for a different variable called `n`, not the one in `main`. Inline functions behave exactly the same as non-inline ones. – Mike Seymour Nov 17 '14 at 18:21

3 Answers3

6

'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.

rafeek
  • 151
  • 4
  • 1
    The issue isn't with the `inline` of the function, but how the parameter is passed. The OP is modifying a **copy** of the passed variable, not the actual variable. – Thomas Matthews Nov 17 '14 at 18:06
  • The question was explicitly "How does an inline function work?", not "How can I make this modify the value of 'n'?" – rafeek Nov 17 '14 at 18:12
5

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

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.

ravi
  • 10,994
  • 1
  • 18
  • 36