Why does it return 0 when a[-1]? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why does it return 0 when a[-1]?

int main() { int a[0]; cout<<a[-1]; return 0; } I was asked this question in the C++ challenge. Can someone please explain why? Thankss

1st Dec 2019, 8:38 AM
Joey Lim
Joey Lim - avatar
4 Answers
+ 8
If you think that the "return value" is what the cout statement is printing , you are wrong , the code will "print" grabage value each time, It does return 0 to the process and it does because the last line is "return 0;"
1st Dec 2019, 8:43 AM
Shahil Ahmed
Shahil Ahmed - avatar
+ 5
Joey Lim I think here we just declared the array but didn't assign any value and accessing the last element of array which is not present that's why it's giving 0 value.
1st Dec 2019, 8:50 AM
A͢J
A͢J - avatar
0
FlamingArrow yeah, i know the output is 0,not because of the "return 0"
1st Dec 2019, 8:45 AM
Joey Lim
Joey Lim - avatar
0
Thanks ppl! now i understand!
3rd Dec 2019, 8:29 AM
Joey Lim
Joey Lim - avatar