0

could anyone clarify this piece of code for me? I've done some research to understand references and static, but I still don't understand what does static do in this example. And why does it have to be there in the first place (If static is missing, the compiler gives warning and program could possibly crash, why?).

int & foo(int b)
{
    static int a = 7;


    a += b;
    return a;
}

int main() {

    int & x = foo(0);
    int & y = foo(1);
    cout << (x + y);

}
François Andrieux
  • 26,465
  • 6
  • 51
  • 83
Meio
  • 109
  • 5

1 Answers1

7

A static local variable will have a life-time of the full program. A reference to it will never become invalid.

Otherwise, non-static local variables will "disappear" once they go out of scope (which happens when the function returns), and you can't have a reference to something that doesn't exist.

An important note about static local variables and their initialization: They are initialized only once, on the first call of the function. The variable will not be initialized on further calls, but will keep the last value it had.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585