Though my compiler (GCC 4.9.2) doesn't complain in the first instance, |
Well if you have your compiler properly configured it would do more than just "warn" you it would fail to compile.
||=== Build: Debug in testcpp (compiler: gcc 6.1.0) ===|
main.cpp||In function ‘int main()’:|
main.cpp|7|error: ISO C++ forbids variable length array ‘arr’ [-Wvla]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
|
From here on I will be using an array that has a size that is a compile time constant, therefore avoiding the nasty VLA issues.
when x = 3, arr[4] is now 'lost' much like an object on the heap whose pointer has been deleted |
Again with a properly configured compiler, if x were 3 you would get a compile error, assuming you have more initializers than the size of the array.
||=== Build: Debug in testcpp (compiler: gcc 6.1.0) ===|
main.cpp||In function ‘int main()’:|
main.cpp|7|error: too many initializers for ‘int [3]’|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
when x = 5, a spurious number from memory is printed as arr[5]. Both, of course, are to be avoided. |
I suppose you mean arr[4] since arr[5] is not a valid element of the array and trying to access an array of size 5 with arr[5] is an array out of bounds error, which produces undefined behavior.
But accessing arr[4] (the fifth element) doesn't print a spurious value. Since you have only partially initialized the array any element that you didn't supply a value was "default" initialized, so all the array elements are properly initialized, int this case arr[4] has a value of 0.