Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interesting case of shadowing parameter C++ (parameter not shadowed in an if block) [closed]

Tags:

c++

gcc

shadowing

I surprising discovered today that the following code is completely valid (gcc 4.4.5):

int get_int(const int& i)
{
    if(i == 0)
    {
        int i = 1;
        return i;
    }
    return i;       
}

I am really surprised. If I have to accept it, then sure I can say that it sort of makes sense because the new variable is within its own block, so the rest of the code outside can still access the parameter, so the parameter is not really shadowed. But it still doesn't make sense to me why did we NOT make this an invalid syntax? I see no benefits of allowing this, and in fact, I just had to dig into a bug caused by this. It was a long function and I created my own variable without realizing it has the same name as a parameter, and some lines of code later(same block) there is a dependence on that very parameter variable, and boom now it is using my version and there goes an hour of my day.

I have very surface knowledge about compilers, so could somebody explain to me the full story behind this behavior? As a comparison, in Java code like this is invalid (duplicate variable).

like image 230
user1861088 Avatar asked Nov 27 '22 18:11

user1861088


1 Answers

If you're asking why C++ allows this, the answer is simple: In order to accept valid C code.

It also makes the rules simpler, to handle different meanings for the same identifier in different scopes all the same way, without caring whether the scopes involved are namespaces, classes, functions, or block scopes.

like image 181
Ben Voigt Avatar answered Dec 21 '22 10:12

Ben Voigt