In C++, why is it possible to index values out of an array, and what is the value returned? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

In C++, why is it possible to index values out of an array, and what is the value returned?

int arr[3] = {1, 2, 3}; cout << arr[5];

29th Jan 2019, 8:16 AM
Mixia
Mixia - avatar
2 Answers
+ 3
In C++ an array is like constant pointers with some limitation and nothing more. You are allowed to go out-of-bound because dont exist a mechanism that prevent you to do it and that derive fron fact that C++ assume that programmer know what do (beside for performance reasons). The value of an out-of-bound array access depends from many things like compiler, function calling type, context etc. At example, try to run this code: #include <iostream> using namespace std; int main() { int t= 11; int a[3]={0,1,2}; cout<<a[3]; return 0; } On SL will be printed 11 and it seem the value of t var... Try to change the t var and run again for assert that. This happen because SL backended compiler, push every variable in order into the stack and because the stack grow into lower adresses (eg. last pushed item has a lower adress respect previous pushed item) an access to a[3] mean &a+3 that is the adress of t var in memory which deferencied you get the value of t
29th Jan 2019, 8:43 AM
KrOW
KrOW - avatar
+ 3
Thank you for the explanation
29th Jan 2019, 8:53 AM
Mixia
Mixia - avatar