Say I have a C++ function:
void foo(int x) {
static int bar = x;
}
If I call foo(3)
then afterwards call foo(4)
, it is my understanding that the value of bar will still be 3. Why is this? I understand why the memory allocation part of the initialization is redundant. but why is the assignment also ignored?
It is not an "assignment". It is an initialization. And, per rules of C++ language, initialization of static objects is performed only once - when the control passes over the declaration for the very first time.
In your example, the control passes over the declaration of bar
when x
is 3
. So, bar
is initialized with 3
. It will never be "reinitialized", i.e. calling foo(4)
will not affect bar
at all. If you want to change the value of bar
after that, you have to modify bar
directly.
Short answer: because the standard says so.
Long answer: that's not an assignment, but an initialisation, and it's ignored because the standard says so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With