Is one variable in nested loop alright?

Jun 5, 2013 at 4:42pm
1
2
3
4
5
6
7
8
for(unsigned short int i = 1; i <= 10; i++)
{
    for(unsigned short int i = 1; i <= 10; i++)
    {
        cout << 0;
    }
    cout << endl;
}


First, the variable in the nested loop was j and after I changed it to i, it works too.
Jun 5, 2013 at 4:49pm
Just because you can doesn't mean you should. Once you started using the variable i in the code it would be extremely confusing to anyone reading it.
Jun 5, 2013 at 5:19pm
According to the C++ Standard

A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition. If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed


For example a C# compiler will issue a compilation error in such a situation.
So it is better do not do such a way.
Topic archived. No new replies allowed.