-3

obj.num has 2 different values but the value of y doesn't change. Does this have to do with initialization vs. assignment? It's something I can't quite wrap my head around.

class A {
public:
    int num;
    A(int num): num(num) {}
};

int get_number(int x) {
    A obj = A(x);
    static int y = obj.num;
    return y;
}

int main() {
    std::cout << get_number(2) << std::endl;
    std::cout << get_number(3) << std::endl;
    return 0;
}
ps22222
  • 3
  • 2

1 Answers1

3

Static local variables are defined once and only once for a function, when the function is first called. Once it's defined and initialized it will never be redefined or reinitialized.

To modify the value of any variable, static or not, one must assign to it.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • What happens the second time y is "initialized"? Does the compiler just ignore the code? – ps22222 Apr 21 '21 at 18:16
  • @ps22222 That's right, it's already defined and initialized. It won't happen again no matter how many times you call the function. Otherwise it wouldn't be any difference from "normal" non-static local variables. – Some programmer dude Apr 21 '21 at 18:16
  • @ps22222, in other words, `static int y; y = obj.num;` would achieve the expected result. – anastaciu Apr 21 '21 at 18:20
  • @Someprogrammerdude Thank you - I was confused because I expected the compiler would throw some kind of error if there's an attempt to re-initialize the static variable. – ps22222 Apr 21 '21 at 18:25
  • @ps22222 No such luck on the error message. The ability to have thread-safe, one time initialization is too handy to go without. Lazy initialization of a single instance of an object, for example. – user4581301 Apr 21 '21 at 18:57