3

Possible Duplicate:
file scope and static floats
What are static variables?

Here is a code from a book.

class X
{
   int i;
public:
   X(int ii = 0) : i(ii) {cout<<i<<endl;} // Default
   ~X() { cout << "X::~X()" << endl; }
};
void f()
{
  static X x1(47);
  static X x2; // Default constructor required
}

int main()
{
  f();

   return 0;
}

My question is why would I like to declare an object as static like in function f()? What would happen if I did not declare x1 and x2 as static?

Community
  • 1
  • 1
macroland
  • 973
  • 9
  • 27

4 Answers4

1

The first time the function f() is hit the statics will be initialized (lazy loading). Had they not been declared static then they would be local variables and recreated every time you called function f().

All calls to f() will result in using the same x1 and x2.

Science_Fiction
  • 3,403
  • 23
  • 27
  • Thanks for the explanation. It seems that even if I have a new function in global space and call f(), it has no effect when static is used and when static is not used f() is called again. – macroland Oct 13 '12 at 18:56
1

For this code it makes no difference to the observable behavior of the program.

Change main to call f twice instead of only once, and observe the difference -- if the variables are static then only one pair of X objects is ever created (the first time f is called), whereas if they're not static then one pair of objects is created per call.

Alternatively, change main to print something after calling f. Then observe that with static, the X objects are destroyed after main prints (the static objects live until the end of the program), whereas without static the objects are destroyed before main prints (automatic objects only live until exit from their scope, in this case the function f).

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
0

The difference between

int f()
{
      int i = 0;
      ++i;
      return i;
}

int f2()
{
     static int i = 0;
     ++i;
     return i;    
}

int main()
{
      for (int i = 0; i < 10; ++i) { cout << f1() << ' ' << f2() << endl; }
}

Is that f1 will always make a new local variable i and set it to zero then increment it, while f2 will create a static local variable i and initialize it to zero once and then each call it increments it from the previous call value.

0

Here is some code to test what does a static object within a function mean:

#include <iostream>

using namespace std;
class A {
  public:
   void increase() {
     static int b = 0;
     b++;
     cout << "A::increase: " << b << endl;
   }
};
int main() {
        A a;
        a.increase();
        a.increase();
        a.increase();
        return 0;
}

And the output is:

A::increase: 1
A::increase: 2
A::increase: 3

Notice the value of b is kept between function calls? Here is the example on ideone so that you can play with it.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176