Reputation: 1081
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;
}
Upvotes: 3
Views: 192
Reputation: 4571
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.
Upvotes: 2
Reputation: 8215
This has nothing to do with the function being declared inline.
The integer is passed by value, i.e. the int x
in 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)
Upvotes: 2
Reputation: 118302
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.
Upvotes: 6
Reputation: 1346
inline functions are not macros, it's only an optimization method and the behavior is same as normal functions.
Upvotes: 3