I'm a bit confused at this situation:
#include <iostream>
void function(int origin)
{
if (origin < 0)
{
double origin = 0.3;
std::cout << origin << std::endl;
}
}
int main()
{
function(-4);
}
where it gets compiled and run successfully using VS2013 under v120 ToolSet. Isn't it wrong C++? 'Cause doing the same but just in the beginning of function it gives a compile-time error.
I don't mind this C++ behaviour. Sure, it can lead to bugs/oversights as you have demonstrated. But you can do this in C++
for (int i = 0; i < 4; ++i) {
for (int i = 0; i < 5; ++i) {
cout << i;
}
cout << i;
}
cout << endl;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 5; ++j) {
cout << j;
}
cout << i;
}
and the results are identical because i
is redefined in the scope of the inner for
loop to be a different variable.
In other languages like C# you can't do this. It will tell you have tried to redeclare a variable of the same name in an inner scope.
I find this over-protective. When I'm cutting and pasting code with loops, it is irritating to have to redeclare i
, which we all tend to use as the loop variable, to be i1
, i2
etc. I invariably miss one, with cut-and-paste code, so I'm using arr[i]
in an i3
loop, when I meant arr[i3]
(whoops).
In production code, I agree that defensive coding means you should use different names for loop variables in the same function.
But it's nice to be able to reuse variable names in nested for loops when you're experimenting. C++ gives you that choice.