-2

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 ? Why does not compiler showed error for declaring again an existing variable, during second iteration in the (first)loop ?

Also please tell why these codes are showing different result :

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

    for(i=0;i<5;i++)
    {
        static int n=0;
        n++;
        cout<<n<<endl; //Print 1 2 3 4 5
    }
IY4
  • 160
  • 1
  • 7
  • 3
    " static variable n is declared again then, why it is retaining its previous value" because that's the point of static variable. – Xaqq May 22 '15 at 08:53
  • Did you expect them to have the same result? Why? – eerorika May 22 '15 at 08:56
  • Why does not compiler showed error for declaring again an existing variable, during second iteration in the (first)loop ? – IY4 May 23 '15 at 09:44

2 Answers2

0

The variable n in the for loop is different from the static one, because their scope is different. If you delete declaration int n in the if loop you will see output as 6 7 8 9 10.

mehmetfa
  • 199
  • 3
  • 15
0

The name "n" has the same scope in both cases - the loop's body.
(Scope is a property of names, not of objects.)

The first loop has one variable, whose lifetime begins at its declaration during the first iteration and ends when the program exits.
The initialisation is only performed when its lifetime begins.

The second loop has a separate variable named "n" for each iteration of the loop.
Their lifetimes begin at the declaration and end when the iteration finishes.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82