3

In case of an Inline function, the compiler copies the whole function from where it has been called. If I follow that instruction the o/p of the programme should be "2010" but it shows the o/p "2020". Why is it so? Did I misunderstand the definition of Inline function? The code goes below:

#include<iostream> #include<cstdio> using namespace std; inline void f(int x) { printf("%d",x); x=10; } int main() { int x=20; f(x); printf("%d\n",x); return 0; } 
2
  • Did I misunderstood the definition of Inline function? Probably. You need to pass the value by reference. Currently you copy the value when you call f(int) and change the copy. Commented Feb 16, 2016 at 11:45
  • Inlining cannot change the behaviour of a well-formed program. Commented Feb 16, 2016 at 11:47

4 Answers 4

6

The fact that the function is inlined does not change the function's semantics.

The function receives its parameter by value, so the only thing that it modifies is its own parameter. It does not modify the value of the "x" variable in main().

By having this function inlined, the function's logical semantics remain unchanged. It still modifies only its own parameter's value, and has no effect on the value of "x" in main(), and its inlined status does not change that.

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

Comments

3

inline functions are not macros, it's only an optimization method and the behavior is same as normal functions.

Comments

2

This has nothing to do with the function being declared inline.

The integer is passed by value, i.e. the int xin the function is a copy of the one passed to the function. The copy is then modified to 10 and gets out of scope when the function is left. The original variable remains unchanged.

If you want to modify the argument, pass by reference, i.e change the function head to inline void f(int &i)

Comments

2

The compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. It does not change the behavior of the function or the program.

You still need to pass x by reference, not by value, in order to modify it.


Also, calling a function inline only gives a suggestion to the compiler. In most cases, the compiler will make a function inline without the programmer interfering, for optimization.

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.