I have been using arrays for a while now.
I have a few questions that i need to ask.
Now I know i cant use an array without giving a value its element(s).
For example this would give me an error
int fly[5];
cout << fly[4] << endl;
And if i print an element that doesn’t have a set value it would give an error:
int fly[5];
fly[2] = 1;
cout << fly[4] << endl;
Now I found if I give 1 element of the array any number in the array intialization. Then the rest of the elements are set to 0.
So this code prints 0
int fly[5] = {15};
cout << fly[4] << endl;
Why does this happen. Can anyone explain?
It happens because the C++ language standard says it should happen. The standard says it should happen because it’s sensible behaviour and saves a lot of typing in cases where you want a large array initialized.
Your first couple of examples produce undefined behaviour, in that the value of those array elements can be anything, but they shouldn’t “give an error”. (A sufficiently clever compiler might issue a warning.)