regarding static variables

hi all,

lets take a code

class A
{
static int i;
func()
{
i++;
}
}

i have studied that to think about problems due to multithreading when we use static variables in our designing

please help me in understanding the above statement by taking above code as example
please use code tags. And when you say multithreading, what are you multithreading? do you men func()?
The point of a static variable is that it retains its value when it goes out of scope..

Ill explain further after I write a sample program

Run this program hope it helps you:
If you have any further questions please ask.
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
#include <iostream>

using namespace std;

void myFunc1(); // function with non static var
void myFunc2(); // function with static var

int main()
{
    for (int i = 0; i < 5; i++) { // when you run the program notice that i for 
        myFunc1();//function 1 aways gets reset back to 0 while function2's i 
        myFunc2();//increments and retains its previous value.
    }
    return 0;
}

void myFunc1()
{
    int i = 0;
    cout<< "Non static var " << i << endl;
    i++;
}
void myFunc2()
{
    static int i = 0;
    cout << "This is static var: " << i << endl;
    i++;
}
Last edited on
Topic archived. No new replies allowed.