+ 5

Array with negative index

Why below code results in value of output as zero? Shouldn't it cause as out of index erro int main() { int a[1]; cout << a[-1]; }

18th Mar 2018, 3:50 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 3
I suppose C++ don't have "index out of range" error like Java does. So, if we try to access it tends to show the content in the memory location corresponding to the created array. For instance, when we create int array of size 2 and say it's in the locations 1000 and 1002. when we try to access array[2], it would give the value stored in 1004 which mostly would be 0
18th Mar 2018, 5:33 PM
Abhishek
Abhishek - avatar
+ 2
arrays index always start with zero, because initialize memory from zero. in all languages same concept used.
21st Mar 2018, 2:01 PM
Gajendra Parmar
Gajendra Parmar - avatar