I just found out about this:
static int x = x;
Why is this initialization accepted by the C++ compiler?
I would call it a compiler anomaly, but someone might come with a good explanation for this.
So for data with static storage, it is possible to initialize a variable with itself... I've tried this with a VS2015 and VS2017 compiler and also some other online C++ compilers.
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code. These variables are allocated in .
As static variables are initialized only once and are shared by all objects of a class, the static variables are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
It's actually the same for static
and non-static
variables.
A name becomes visible immediately after its declarator and before its initialization, if any. Thus in
static int x = x;
the name x
becomes visible immediately after its first occurrence, and can be referred to in the initializer. Since it's static, its initial value is well defined (it's 0
).
This is also legal, even at block scope:
int x = x;
although here you're likely to get a warning because x
is being initialized with its own indeterminate value (the behavior is undefined in most cases).
It's a silly thing to do, but C++ isn't in the business of going out of its way to prevent you from doing silly things. As an example, you might want to declare a pointer that points to itself:
void *p = (void*)&p;
Here the initializer refers to the address of p
rather than its value, but the name p
has to be visible to make that work. It wasn't considered worthwhile to add a special-case rule.
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