My question is pretty straightfoward: why can I assign a value that goes out of bounds to an array like this, but not with the {} operator:
int arr[2];
arr[2] = 2;
for(int num{0}; num < 3; num )
cout << arr[num] << endl;
But when I do this I get an error right from the start:
int arr[2] {1,2,3};
Now I know that assigning a value beyond the scope of the array may cause an undefinied behavior, as this questions has clarified to me:
Accessing an array out of bounds gives no error, why?
But why can't I go beyond the arrays' limit in the second case? Even though it is wrong - And I don't intend to do it - I'd like to know the difference in these cases.
CodePudding user response:
Both cases are completly different. The first one is array element assignement. The second is array initialization. The rules state that it is an error if you provide more initializers that the array can hold. The rules state also, that element access behind the array end is not an error but undefined behaviour. In other languages, there is bound checking at runtime for array access, but not in C . So the reason it behaves like it does, is that the C standard commitee decided so.
You could of course ask why the C standard commitee decided so. I think the answer is, that C tries to be as backward compatible as possible and the rules for array element access have always been that way.
Also the initialization can be evaluated and checked at compile time, whereas the element access happens during runtime and the compiler cannot foresee if there is actually an access behind the end of the array.
