Scope and Lifetime of variables inside "for" loop in c++

why these codes are showing different results :

for (int i = 0; i < 5; ++i)
    {
        static int n = 0;
        n++;
        cout<<n<<endl; // prints 1 2 3 4 5
    }

    for (int i = 0; i < 5; ++i)
    {
        int n = 0;
        n++;
        cout<<n<<endl; // prints 1 1 1 1 1
    }

if static variable n is declared again then, why it is retaining its previous value.
What exactly is happening with the scope of static variable inside “for” loop ?


Source: c++

Leave a Reply