lundi 31 décembre 2018

How can range-based for loops work with simple arrays?

Behold, here we have a simple array and we are printing all the elements in the array using a range-based for loop, and it actually works! Not surprising for many programmers but it's surprising for me.

The advantage of using std::vector or std::array is that it's a class which holds the size of the internal array as a data member. However, so such size information is stored when you are using a raw/simple/primitive array. It's your responsibility as the programmer to carry around the size of the array with you whenever you want to loop through the array.

My question is, how can a range-based modern C++11 for loop print all the elements in the array without being explicitly given the size. I know that the name of the array is simply a pointer to the first element. Without having the size, once you start looping, you don't know when to stop because you don't necessarily know how far the array extends in memory. And yet the range-based for loop works. How does it do that?

C-strings store a special \0 character to denote the end of the usable memory. Examining the memory after the int myarray[SIZE] using gdb, I found what I take to be garbage values.

const int SIZE = 5;
int myarray[SIZE];
myarray[0] = 0;
myarray[1] = 1;
myarray[2] = 2;
myarray[3] = 3;
myarray[4] = 4;

for (int i : myarray)
  cout << i << ' ';

Aucun commentaire:

Enregistrer un commentaire