Why does using the same count variable name in nested FOR loops work?

前端 未结 5 592
予麋鹿
予麋鹿 2020-12-16 16:07

Why does the following not give an error?

for (int i=0; i<10; ++i) // outer loop
{
    for (int i=0; i<10;++i) // inner loop
    {
    //...do somethin         


        
5条回答
  •  甜味超标
    2020-12-16 16:16

    The C++ compiler accepts this as valid, as the scope of the second is only within the { } braces. If you implement the same in C, you will see an error like this:

    $ gcc test.c
    test.c: In function ‘main’:
    test.c:10: error: ‘for’ loop initial declaration used outside C99 mode
    test.c:12: error: ‘for’ loop initial declaration used outside C99 mode
    

    This is illegal in most C dialects; it is a legal C++ declaration, and so may be accepted if you are compiling C with a C++ compiler:

    for( int i=0; i<5; ++i){}
    

    It is common to have a loop iterator only in the scope of the loop in C++, but C makes sure (specially with the C90, not C99), that the declaration is outside the scope of the loop. Hope that helps ... :-)

    So, when you declare another FOR loop within the older one, then the scope start fresh and your code compiles without any error in C++ or C99. This is the usual accepted norm for a scope declaration.

提交回复
热议问题