0
#include <iostream>
using namespace std;

int main() {
    int var; // default initialization var = 0 Why?
    cout << var << endl;    
    return 0;
}

If i understand default initiaization right, int variable must be indeterminate value.

The effects of default initialization are: 1) if T is a non-POD (until C++11) class type, the constructors are considered and subjected to overload resolution against the empty argument list. The constructor selected (which is one of the default constructors) is called to provide the initial value for the new object; 2) if T is an array type, every element of the array is default-initialized; 3) otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

So, why int var equal 0 in that case?

Artem Sh
  • 3
  • 2
  • Yes it is indeterminate value. Trying to output an indeterminate value causes undefined behaviour. Undefined behaviour means anything can happen. Printing 0 is a possible case of "anything". – M.M Jun 15 '16 at 03:34

1 Answers1

1

Your understanding is correct. var here contains garbage value here, it just happened to be 0.

Garbage value doesn't have to be some seemingly random value, usually it's the value that happened to be in that memory. Run your program again, or change a different compiler, probably you'll see a different result.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    Disapproval. There are a tonne of duplicates on this site which would be better to link to than answer – Tas Jun 15 '16 at 03:35
  • Here the OP knows the rule of default initialization. He just misunderstood that `0` could be one possible value of garbage value. I didn't find the duplicate that answers this particular question. – Yu Hao Jun 15 '16 at 03:38