1

i have the following:

   class base
   {
      public
       void f();
       ...
   }
    void base::f()
    {
        static bool indicator=false;
         .....
         if(!indicator)
         {
            ...
            indicator=true;
          }
     }
    class D:public base
    {      
       ...
     }

in my main() i have:

      main()
      {
          // first instance of D
          base *d1 = new D();
          d1->f();
           ....
           // 2nd instance of D
          base *d2 = new D();
          d2->f();
       }

i find that the first time i instantiate D and call d1->f() the static variable is set to false. but the 2nd time i call d2->f() the code does not even hit the line "static bool indicator=false;" and it is kept at true (from the first pass of d1-f()) This is exactly the behavior i want but i do not understand why this is happening. can someone please explain what is happening. thanks in advance

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
user1612986
  • 1,373
  • 3
  • 22
  • 38
  • By design, the initializer is run only once for static variables within a function. If you didn't want that behavior, then you would just declare the variable as non-static. The point is to maintain the value through multiple calls of the function. – Lou Feb 23 '13 at 03:21

2 Answers2

10

Static variables declared in member functions will keep their value between function calls. There will be only one copy over all instances, and all accesses to indicator from different instances will affect the same indicator. This means indicator will only be initialized once.

See here for more info: Static variables in member functions

Also this code does not toggle indicator, it always sets it to true if it's false (which I'm sure is the behaviour you want).

if(!indicator)
     {
        ...
        indicator=true;
      }
Felix Glas
  • 15,065
  • 7
  • 53
  • 82
  • not your fault, but the title of the question you link is a bit confusing, because "class methods" can be understood as refering to static methods. – 463035818_is_not_an_ai May 05 '18 at 08:49
  • 1
    @user463035818 Yes, agreed. The correct C++ term would be "member functions". I've updated the title in the referenced question. – Felix Glas May 05 '18 at 12:16
3

This is precisely the behavior of static variables declared inside function blocks. It has been like that since the introduction of the feature in the C programming language.

The static declaration can also be applied to internal variables. Internal static variables are local to a particular function just as automatic variables are, but unlike automatics, they remain in existence rather than coming and going each time the function is activated. (K&R, page 61).

The static initializer is executed before the first invocation of the containing function. Being static, the variable retains its last state across the invocations.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523