By far the best choice is to rename the function parameter so it does not conflict with the global variable, so there is no need for circumventions.
Assuming the rename option is not acceptable, use ::foo
to refer to foo
at the global scope:
#include <iostream>
int foo = 100;
int bar(int foo)
{
int sum = foo + ::foo; // sum adds local variable and a global variable
return sum;
}
int main()
{
int result = bar(12);
cout << result << "\n";
return 0;
}
Collisions between local and global names are bad — they lead to confusion — so it is worth avoiding them. You can use the -Wshadow
option with GCC (g++
, and with gcc
for C code) to report problems with shadowing declarations; in conjunction with -Werror
, it stops the code compiling.