I've got a function that has a parameter with the same name as a for loop control variable :
1 2 3 4 5 6 7 8 9 10 11 12 13
void fun(constint& i = 0)
{
std::cout << "&i: " << &i << "\n";
for (int i = 0; i < 3; i++)
{std::cout << "loop &i: " << &i << "\n";}
std::cout << "&i: " << &i << "\n";
}
int main()
{
fun(1);
return 0;
}
I'd half expected that complier will yell at me for redefining the i variable but it compiles and runs just fine. Both i variables have different addresses.
I know that it's probably a bad design, even if its a defined behaviour (is it ?). Is there any way to access the "outside" i variable inside the for loop ?
The reason it works in your code, is becuase you created the other variable inside the for-loop. So it is only defined inside the for-loop.
1 2 3
for (int i = 0; i < 3; i++)
{std::cout << "loop &i: " << &i << "\n";} // Its recognized here.
// Not recognized it. It goes out of scope one the for-loop is done.
Edit: Another example.
1 2 3 4 5 6 7
if(something)
{
int x = 5; // create variable
x = 10; // change its value, works fine
}
x = 15; // Does not work, becuase x was created inside the if statement, and does not exist outside of that.