int tar = 0;
{
int tar = tar;
cout<<tar;
}
It prints out 814005873, but what I expected was 0.
int tar = 0;
{
int tar = tar;
cout<<tar;
}
It prints out 814005873, but what I expected was 0.
The variable in the outer scope is not relevant. You'd get the same with
{
int tar = tar;
cout<<tar;
}
tar
is not initialzed hence using its value to initialize itself is undefined behavior. All major compilers warn about such case of tar
being used uninitialized. For example: https://godbolt.org/z/3x437P46K. Don't ignore warnings!
It may look weird that this isnt an error, but for a custom type such initialization can be meaningful. For example:
struct foo {
foo& other;
foo(foo& other) : other(other) {}
};
int main()
{
foo f = f;
}
f
holds a reference to itself.