static variable inside a function

Hi,

is there any reason for declaring a local variable inside a function as static?

thanks
A static variable has a global lifetime but with local scope. This lets you have the benefits of having a singular global and the organizational benefit of keeping the scope local.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void CountIt()
{
  static int count = 0;

  ++count;
  cout << count << "\n";
}

int main()
{
  CountIt();  // prints 1
  CountIt();  // prints 2
  CountIt();  // prints 3, etc
}
Yes, the static variable will retain its value between calls.
Nope.......a static variable is referred to once and once only.
?

What do you mean "referred to"?

It's initialized only once (barring some unfortunate multithreaded race condition) -- but it can be accessed as many times as the program likes.
It's initialized only once (barring some unfortunate multithreaded race condition)
Static and global data is initialized before main() is called, one object at a time. There's no room for race conditions because it's all ran from a single thread.
local static variables are initialized on first use. If the function is called at the same time from 2 threads, you could have a race condition.

edit:

illustration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

class A
{
public:
    A()
    {
        cout << "A ctor\n";
    }
};

void func()
{
    static A a;
}

int main()
{
    cout << "main starting\n";
    func();
    return 0;
}
Last edited on
Topic archived. No new replies allowed.