I know that local variables in C & C++ aren't automatically initialized & if no initial value is given to them they have garbage values. I also know that global & static variables are by default initialized to zero. Use of uninitialized variable results in undefined behavior in C++.
But recently I tried following simple C++ program on various implementations of C++ & all gives me 0 as output.
#include <iostream>
int main()
{
int u;
std::cout<<u<<'\n';
}
Output:
CodeBlocks 13.12 IDE: 0
Orwell Dev C++ 5.8.3: 0
Ideone.com: 0 (visit this: http://ideone.com/zWrgwo)
Is it true that modern compilers automatically initializes local variables to 0? or such type of program still represents undefined behavior ? Is it guaranteed to see 0 as output on every modern implementation of C++ always?
Specific implementations are free to not set them ("local" variables) to anything, or to set them to any value they want, including zero. The standard doesn't mandate they they be set to a non-zero value, after all :-)
The standard merely states that their value, if not explicitly set, is undefined. Hence it's not something a good programmer would rely upon. This is covered in C++11 8.5 Initializers [dcl.init] /11
(my emphasis):
If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value.
So, in answer to your closing question, is it guaranteed to see 0 as output on every modern implementation of C++ always?
, the answer is no, plain and simple.
As an aside, you may well find that the three "separate" environments you tested on, CodeBlocks
, DevC++
and ideone
, are all using the same compiler under the covers, so it would hardly be an exhaustive test in that case.