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 ?

5
  • When should I write the keyword 'inline' for a function/method? Commented Nov 17, 2014 at 17:55
  • 1
    A function's logical behaviour is identical whether it is inline or not. Commented Nov 17, 2014 at 17:56
  • Pass by reference. You increment a copy of the parameter, and the copy disappears after the execution leaves your function. Commented Nov 17, 2014 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. Commented Nov 17, 2014 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. Commented Nov 17, 2014 at 18:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
The question was explicitly "How does an inline function work?", not "How can I make this modify the value of 'n'?"
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.