Static and automatic variables

Why the value y=11 after lopping and only the value of x changed.
Can anyone help. I didn't understand at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//Program: Static and automatic variables
#include <iostream>
      
using namespace std;

void test();

int main()
{
    int count;

    for (count = 1; count <= 5; count++)
        test();
	system ("Pause");
    return 0;
}

void test()
{
    static int x = 0;
    int y = 10;

    x = x + 2;
    y = y + 1;
	
    cout << "Inside test x = " << x << " and y = "
         << y << endl;
} Put the code you need help with here.


Output
1
2
3
4
5
Inside test x =2   and y =11
Inside test x =4   and y =11
Inside test x =6   and y =11
Inside test x =8   and y =11
Inside test x =10   and y =11
Its because you made x a static variable. This link might help you understand what static variables do.
http://www.cprogramming.com/tutorial/statickeyword.html
Last edited on
Ok thanks for that link fabtasticwill.
When we declared x as the static variable the value of x will changed but when we just declared y is int it will not changed anything.

Is this true?
Topic archived. No new replies allowed.