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", ie 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.
The memory location for bar
is not valid until the first call to foo
, which is when bar
gets instantiated. bar
gets initialized to x
when it gets instantiated. Every call to foo
afterward, bar
is already instantiated and therefore already initialized.
this is initialization of static variable instead of assigning values to it. with that being said, the value of bar would always be 3 if u call foo(3) at the very first place.
Consider some different static variables:
void foo(int x) {
static int bar = x;
static std::string s1 = "baz";
static std::string s2("baz");
static int i{2}; // C++11-style uniform initialization
}
Do you also think s1
should get "assigned" the value "baz"
every time the function is called? What about s2
? What about i
?
None of those statements perform any assignment, they are all initializations, and they are only done once. Just because a statement includes the =
character doesn't make it an assignment.
A reason why the language is defined to work that way is that it's common to use a local static variable to run a function once:
bool doInit()
{
// run some one-time-only initialization code
// ...
return true;
}
void func() {
static bool init = doInit();
// ...
}
If init
got assigned a value again every time the function is called then doInit()
would get called multiple times, and would fail its purpose of running one-time-only setup.
If you want to change the value every time it's called, that's easy ... just change it. But if you don't want it to keep changing then there would be no way to do that if the language worked the way you are asking about.
It would also be impossible to have static const
local variable:
void func() {
static const bool init = doInit();
// ...
}
Oops, this would try to change the value of init
every time it's called.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.