Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to a global variable which has the same name as a local variable in C++?

If there is a global variable and the function has a parameter with the same name, and desired result is the sum of the local and global variable, how can we refer the global function in this particular situation? I know its not good idea to do so. But asking just for curiosity.

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);
    return 0;
}
like image 447
Faisal Naseer Avatar asked Mar 18 '14 22:03

Faisal Naseer


2 Answers

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.

like image 72
Jonathan Leffler Avatar answered Oct 20 '22 15:10

Jonathan Leffler


Use ::foo - but REALLY don't do that. It will confuse everyone, and you really shouldn't do those sort things. Instead, rename one or the other variable. It's a TERRIBLE idea to use the :: prefix to solve this problem.

like image 24
Mats Petersson Avatar answered Oct 20 '22 17:10

Mats Petersson