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
  • 28,148
  • 6
  • 56
  • 87
Meio
  • 121
  • 6
  • 3
    The function returns a reference to `a`. Without the `static`, `a` is on the stack, so the function returns a reference to what? – Blaze Mar 18 '19 at 14:54
  • 1
    what warning? What exactly did you not understand after reading [some docs](https://en.cppreference.com/w/cpp/keyword/static)? – 463035818_is_not_an_ai Mar 18 '19 at 14:54
  • Possible duplicate, but I'm hesitant to hammer: https://stackoverflow.com/q/4643713/10077 – Fred Larson Mar 18 '19 at 14:55
  • very related: https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope – NathanOliver Mar 18 '19 at 14:55
  • also near-duplicate: https://stackoverflow.com/questions/37742649/the-scope-and-lifetime-of-static-local-variable-in-c – Brian Bi Mar 18 '19 at 14:57

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
  • 400,186
  • 35
  • 402
  • 621