My understanding is that an int variable will be initialized to 0 automatically; however, it is not. The code below prints a random value.
int main ()
{
int a[10];
int i;
cout << i << endl;
for(int i = 0; i < 10; i++)
cout << a[i] << " ";
return 0;
}
- What rules, if any, apply to initialization?
- Specifically, under what conditions are variables initialized automatically?
It will be automatically initialized if
MyClass instance;int a[10] = {}(all zeroed) orint a[10] = {1,2};(all zeroed except the first two items:a[0] == 1anda[1] == 2)static(no matter if inside a function or in global/namespace scope) – thanks JerryNever trust on a variable of a plain type (int, long, …) being automatically initialized! It might happen in languages like C#, but not in C & C++.