mercredi 23 août 2017

c++: confusion on const reference used in a nested FOR range usage

I am having confusion on the below. So let me explain simply.

int ia [3][4] =  {
                     {0, 1, 2, 3},
                     {4, 5, 6, 7},  
                     {8, 9, 10, 11}  
                 };

for (const int (&r)[4] : ia)
      for (int &x : r) --> this has error
             x = 1;

The error is "binding value of type 'const int' to reference to type 'int' drops 'const' qualifier".

The reference r to array of int but it's a const reference. That is understandable. The inner for loop using r, it will iterates over the inner array. The r is a const reference to the array but not each item. So why is there error?

I can replace with the below code and it works ..

 for (const int (&r)[4] : ia)
            for (int x : r) --> this has error
                      x = 1;

This i understand. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire