-2
#include <bits/stdc++.h> 
using namespace std;  
int main() 
{ 
    int arr[4]={1,2,3,4};
    for(int i=0; i<6; i++){
    cout << arr[i]<<endl;
    }

    return 0; 
}

I tried running this code in visual studio and I'm getting the output as:

1
2
3
4
4
4200976

After modifying it also, I'm getting arr[n] as the length of the array. So is it always true, and can we assume that it is the most optimised way to get the length of the array?

Anshitgrg
  • 21
  • 1
  • 2
    You are reading past the end of the array, this is undefined behavior, you cannot rely on it. Raw C++ arrays don't know their length, its your job to keep track of it. – Borgleader Jun 08 '20 at 11:13
  • 8
    No, it's not. Today you will get the length of the array. Tomorrow you'll get the winning lottery numbers, there. Next week you'll have the answer to life, universe, and everything, there. This is undefined behavior. – Sam Varshavchik Jun 08 '20 at 11:14
  • 3
    no! you are just printing garbage that is out of the bounds of the array... that data has nothing o do with the array – ΦXocę 웃 Пepeúpa ツ Jun 08 '20 at 11:14
  • @SamVarshavchik 42! – nicomp Jun 08 '20 at 11:14
  • If you want to get the size of an array, (and it hasn't been converted to a pointer), you can do something like `sizeof(a)/sizeof(a[0])`. This should be resolved at compile time and so instantaneous at runtime. – gmatht Jun 08 '20 at 11:19
  • On my machine, prints out the first 4 numbers, then crashes with a `runtime error: index 4 out of bounds for type 'int [4]'` – Eljay Jun 08 '20 at 11:19
  • Obligatory comment: [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) and [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Yksisarvinen Jun 08 '20 at 11:21
  • 1
    This is just a coincidence. That it looks like the size is possibly because you're indexing outside the array and the value of the loop variable happens to be stored exactly "one past the end" of the array. – molbdnilo Jun 08 '20 at 11:42

1 Answers1

3

The behavior of accessing elements outside the bounds of the array is undefined.

and can we assume that it is the most optimised way to get the length of the array?

This isn't a way to get the length of the array.

A correct, and efficient way to get the size of the array is to use std::size(arr).

eerorika
  • 232,697
  • 12
  • 197
  • 326