Static var in member function

greets

bool SomeClass::Function( bool thankYou = true )
{

    static bool justAbool = false;
    // Do something with justAbool;
    ...
}

You have a search, but I can’t find anything about it except the globals or the member functions themselves.

What does the above, that is, what happens, makes justAbool retain its value after exiting the scoop? Or does he “remember” the value again when re-entering the scoop?

thank

+3
source share
6 answers

staticWhen applied to a local variable, this variable is static. This means that the service life justAboollasts until the end of the program, and not until the end of the function call. It remains unchanged, it can be obtained only by name in the function after the declaration.

justAbool ( = false) . , , .

, .

, , ( ). (3.7.1 [basic.stc.static])

bool , , . (3.8 [basic.life])

( ) . (6.7/4 [stmt.decl]) [ , , .]

POD , , , , . (6.7/4)

, , .

+11

justAbool false . . , SomeClass, -. justAbool , , .

+17

, // Do something with justAbool;.

, , static ( justAbool) . . . .

int f()
{
   static int v = 0;
   return ++v;
}
int main()
{
   cout << f() << endl;
   cout << f() << endl;
   cout << f() << endl;
   cout << f() << endl;
}

:

1
2
3
4

-: http://www.ideone.com/rvgB5

+1

justAbool - ​​ . , - , , .

0

justAbool . , ?

0

, :

  • POD: main()
  • non-POD: , .
0

Source: https://habr.com/ru/post/1791649/


All Articles