Question

I've miss-write my variables names using i for two variables, one is an int and the other Uint16 like so :

for(int i = 0; i <= 5; i++) {
    for(Uint16 ch = 5; ch < 20; ++ch) {
        Uint16 i = ch;
        //Some code
        cout << i;
    }
}

Using clang x86 5.1 it does compile, but which i will be displayed ? Is their a special rule ?

Was it helpful?

Solution

In an inner scope, a variable declaration will shadow any previous declaration. In your code sample the output will be the value of ch on each loop iteration.

If you were to output the value of i outside the inner for, the output would be the value of the i declared in the first for loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top