Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this 'for' loop valid?

Tags:

c++

arrays

c++11

The problem is that row is an int * and not a int[4] as one would expect because arrays decay to pointers and there is no automatic way to know how many elements a pointer points to.

To get around that problem std::array has been added where everything works as expected:

#include <array>

int main() {
    std::array<std::array<int, 4>, 3> ia;
    for (auto &row : ia){
        for (auto &col : row){
            col = 0;
        }
    }
}

Note the & before row and col which indicate that you want a reference and not a copy of the rows and columns, otherwise setting col to 0 would have no effect on ia.


To prevent the decay of the int[] to int* you can use &&

int main() {
    int ia[3][4];
    for (auto && row : ia)
        for (auto && col : row)
            ;
}