Consider following code example:
#include <iostream>
static int bar = bar;
int main()
{
int foo = foo;
std::cout << "foo = " << foo << std::endl;
std::cout << "bar = " << bar << std::endl;
}
I get following compiler warning:
main.cpp: In function 'int main()':
main.cpp:7:15: warning: 'foo' is used uninitialized in this function [-Wuninitialized]
int foo = foo;
^
Output:
foo = 0
bar = 0
I expected this warning as foo is used unitialised. Instead of 0, 'foo' can be anything. Self-assignment is undefined.
But why is the the self-assignment of 'bar' not warned? Is this assignment of 'bar' defined or undefined behaviour and why?
I know, static variables of elementar data types are initialised with '0' but in this case, the variable 'bar' is used during its initialisation. I'm wondering, if this is defined behaviour and the '0' is the expected output. (Which would explain, that no compiler warning occurs).