Why does this C ++ work? (variables with the same name)

Well, I want to know why this code works, I just realized that I have two variables with the same name within the same scope.

I am using g ++ (gcc 4.4).

for(int k = 0 ; k < n ; k++)
    {
        while(true)
        {
            i = Tools::randomInt(0, n);
            bool exists = false;

            for(int k = 0 ; k < p_new_solution_size ; k++)
                if( i == p_new_solution[k] )
                {
                    exists = true;
                    break;
                }
            if(!exists)
                break;
        }

        p_new_solution[p_new_solution_size] = i;
        p_new_solution_size++;
    }
+5
source share
5 answers

Well, I want to know why this code works, I just realized that I have two variables with the same name within the same scope.

It looks like you are confused by areas. They are not "located in the same area" ... the for k loop has its own nested / inner area. More importantly, to understand why language allows this, consider:

#define DO_SOMETHING \
    do { for (int i = 1; i <= 2; ++i) std::cout << i << '\n'; } while (false)

void f()
{
    for (int i = 1; i <= 10; ++i)
        DO_SOMETHING();
}

, "DO_SOMETHING", , i. DO_SOMETHING, , - i - , , . - , , , , . , : , .

, , - . , , () ( , : ( , ( - , )).

+4

k ( ) k .

. :

int main()
{
    int a;       // 'a' refers to the int until it is shadowed or its block ends
    { 
        float a; // 'a' refers to the float until the end of this block
    }            // 'a' now refers to the int again
}
+9

, 3.3.1

, , , , , . , , , . , . , . () () .

, .

, , () . , .

, , .

+2

, . , , "" X - X. , .

+1

In C / C ++, the scope is limited by curly braces, so the following code is acceptable for the compiler:

int k()
{ 
    int k;
    {  
        int k;
        {
           int k;               
        }    
    } 
} 
0
source

All Articles