Alf said:
* arnuld:
well, to my *surprise* this works:
#include<iostream>
int x = x;
BUT this did not and i started this post because earlier i tried this: [...]
int main()
{
int x = x;
i want to know the WHY
That's because namespace scope variables (such as the first one) are
zero-initialized first of all, and only then is the stated
initialization, if any, performed.
I thought, that zero initialization takes place *by default*, i.e. only
if there is no explicit initialization.
I'd expect undefined behavior, because the right hand side is not
initialized yet.
There is no automatic zero-initialization of automatic variables, like
the one in your second program.
Agreed.
Thus, the second program's initialization initializes x with itself,
which at this point has an /indeterminate/ value, or in other words,
arbitrary bits, garbage. So the compiler helpfully offers a warning.
Agreed.
You're allowed to do that, or just about anything, but since it's
/usually/ a mistake, the compiler warns about it.
I'd expect, that reading garbage leads to undefined behavior.
I have no standard to look it up, but replacing `int' with
`std::string', my compiler (g++-3.3 -ansi -pedantic -Wall) emits no
diagnosis at all, but the first (static) program causes a "Segmentation
fault", and the second (auto) prints "Aborted". Here's my test code:
#include<iostream>
#include<string>
//std::string stat_s = stat_s; // "Segmentation Fault"
int main()
{
// std::cout << "stat: " << stat_s << std::endl;
std::string auto_s = auto_s;
std::cout << "auto: " << auto_s << std::endl; // "Aborted"
}
My advice to arnuld:
1. Don't do never ever use the _value of x_ in the initializer of x.
2. If you do, don't expect any specific behavior from your compiler. It
may emit a diagnosis, produce illegal instructions, or delete your emails.
But the original question was about using the _name of x_ in its own
initializer. As the value is still undefined, I can imagine only two
formal cases :
1. sizeof( x ) -- but you can use sizeof with the type of x as well here.
2. &x, (or &x.member), which is well defined (the ampersand may be
hidden, if the ctor expects a reference). But remember: you may store
the address, but you must not yet dereference it.