Reputation: 780
Suppose we have the following c++ code:
int a = 10;
inline int add(int x){return a+x;}
void foo(int a, int b)
{
... do something with a ...
std::cout<<add(b);
}
int main()
{
foo(12);
}
For inline function add, the "a" variable it uses is the global variable "a". But, in function call for foo(), we have another local variable "a". If add is not an inline function, it would definately use the global "a", but what would happen in the above code? Is there any rule for it?
Upvotes: 2
Views: 2476
Reputation: 311156
This inline function
int a = 10;
inline int add(int x){return a+x;}
deals with the global variable a
When the compiler parses the function definition it has to know how a
is defined and if there was not the preceding statement with the declaration of a
the compiler would issue an error.
Thus in this function definition the compiler refers to the global variable a
independing on where the function will be inlined.
Also take into account that opposite to lambda expressions functions are unable to capture local variables.
According to the C++ Standard functions may not be defined within other functions. Though some compilers have their own language extensions. In this case you should read the documentation supplied with the compiler that has such an extension.
Upvotes: 4
Reputation: 1
First of all foo
expects 2 arguments so your code as it is now it wont work.
And second since you haven't declared a param with the same name as a variable that has global scope for your add
function it will just use the variable with global scope.
If you would had declared add
as:
inline int add(int a, int b){return a + b;}
the local param a
will mask the one with global scope;
Upvotes: 0