Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Foreach loop with multidimensional arrays in c++

I am getting an error while compiling the following cpp code:

int x[][2]{{1, 2}, {3, 4}};

for (int e[2] : x) {
    std::cout << e[0] << ' ' << e[1] << '\n';
}

This gives the following error:

error: array must be initialized with a brace-enclosed initializer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I did replaced int e[2] with auto e and that worked but I want to work with the actual type.

Is there any workaround?

>Solution :

the correct fixed-size declaration is

for (int(&e)[2] : x) {}

or you can use auto& to deduce it

for (auto& e : x) {} // same as above

note: auto doesn’t deduce the same type

for (auto e : x) {} // e is int*
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading