3

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

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?

1
  • 1
    This would be easier with std::array Commented Dec 16, 2022 at 16:45

2 Answers 2

5

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*
Sign up to request clarification or add additional context in comments.

6 Comments

It works but it seems like we are using a reference type like a reference(int(&e)[2]) or pointer (int *). Though I know that C-style arrays are actually pointers internally. Can't we just use an actual array type like we do in a one dimensional array? Thank you.
@AK-CHP then you'd copy the content, which probably is not what you want. (and yes, you cannot copy raw array type)
I am just hacking. Surely I won't do it in an actual program. I just want to explore whether it can be done :).
@AK-CHP no, you cannot copy raw array that way, in range-based-for or not.
|
2

interpret the inner array as a pointer:

#include <iostream>
   
int main() {
    int x[][2]{{1, 2}, {3, 4}};

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

2 Comments

Surely working, but there's no need to decay the array into a pointer here. auto& would be the better option. +1 nevertheless since it's actually a working solution.
you loose the information of the size of the array. With the pointer you cannot eg use range based loop on the inner array like this godbolt.org/z/e4vE4vcdo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.