Integers in a function

If I call to a function, void MyFunction() and in that function, a variable that is declared inside the function, not received from the main function, is changed or set, will the function have the same variable data when it is called upon again?
Nope
Depends on the storage duration of the variable.

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
#include <iostream>

void foo()
{
      std::cout << "\n*** enter foo ***\n" ;

      int a = ( ( std::cout << "\tinitialize a\n" ), 999 ) ;
      // 'a' has automatic storage duration
      // each time the function is called, a new 'a' is initialized with 999
      ++a ;
      std::cout << "\ta == " << a << '\n' ; // a is now 1000

      static int s = ( ( std::cout << "\tinitialize s\n" ), 999 ) ;
      // 's' has static storage duration
      // the first time the function is called, 's' is initialized with 999
      // the next time the function is called, the same 's' is used
      ++s ;
      std::cout << "\ts == " << s << '\n' ;
      std::cout << "*** exit foo ***\n" ;
}

int main()
{
    foo() ;
    foo() ;
    foo() ;
}

Output:
*** enter foo ***
        initialize a
        a == 1000
        initialize s
        s == 1000
*** exit foo ***

*** enter foo ***
        initialize a
        a == 1000
        s == 1001
*** exit foo ***

*** enter foo ***
        initialize a
        a == 1000
        s == 1002
*** exit foo ***                            

Topic archived. No new replies allowed.