What initialization. In your example, accessing i
is
undefined behavior, since it wasn't initialized. Some compilers
do initialize it, at least in debug mode, but generally with
something like 0xDEADBEEF
or 0xCCCCCCCC
, so that you can
easily recognize in a debugger that you're accessing
uninitialized memory (and so that the program is likely to crash
if you use it as a pointer), but this is not required.
The only time built-in types are implicitly initialized is when
they have static storage duration: variables defined at
namespace scope (include static class members), or local
variables which have been declared static
.
You don't show the context of your code, but if it is directly
in main
, or in the first function called from main
, int i
will be the first use of this actual memory. And the OS
probably will have set it to 0, for security reasons. You might
want to try something like:
void scribble()
{
int x = 0x12345678;
}
void testit()
{
for ( int i; i < 10; ++ i ) {
std::cout << i << '\n';
}
}
int
main()
{
scribble();
testit();
return 0;
}
The call to std::operator<<( std::ostream&, char const* )
is
might have left something different from 0 in this
particular memory cell. (Or the compiler has optimized it out.
Try this with all optimization turned off.) Neither g++ nor
VC++ initialize the i
in testit
.