5

Why the C++ code below can't be compiled?

#include <utility>

int main() {
    int x[6];
    int y[6];
    std::pair<int[6], int[6]> a(x, y);
    return 0;
}

For example MSVC gives the following error:

error C2661: 'std::pair<int [6],int [6]>::pair': no overloaded function takes 2 argument

Thanks for the comments that using C++ alternatives to construct arrays, but I also want to know the reason that the code can't be compiled.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
ConnellyM
  • 173
  • 7
  • 3
    Use `std::array` instead of c arrays: [https://ideone.com/eEKplR](https://ideone.com/eEKplR) – drescherjm Mar 17 '23 at 14:49
  • 2
    @BRemmelzwaal: `int[6]` certainly is a type. – Ben Voigt Mar 17 '23 at 14:51
  • 3
    C style arrays will either not work or not behave as you expect in many contexts. Prefer C++ alternatives. – Drew Dormann Mar 17 '23 at 14:51
  • 1
    an array decays into a pointer when passed into a function, which results in `int*`. Which means `int* != int[6]`. You should use a `std::array` or wrap it into a struct yourself. – Raildex Mar 17 '23 at 14:56
  • 3
    Arrays are not copyable in C++ (i.e. if `a` and `b` are arrays you cannot write `a = b;`). This makes using them in templates (and many other places) problematic. – john Mar 17 '23 at 15:02
  • Because of [array to pointer decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). In particular, `a` and `b` decay to pointers to `int` in your example. Also built in array assignment `array1 = array2;` is not allowed. [Arrays cannot appear on the left hand side of assignment operator](https://stackoverflow.com/questions/25987133/array-type-is-not-assignable) – Jason Mar 17 '23 at 15:03
  • Just to be clear, the primary problem here isn't that arrays decay to pointers. It's that arrays aren't copy-assignable. – Jerry Coffin Mar 17 '23 at 15:24

1 Answers1

11

Using int[] as a type of element in a std::pair is actually allowed.
For example you could use:

std::pair<int[6], int[6]> a;
a.first[0] = 1;

What's not valid is the initialization of the pair with (x,y). C arrays are not copy assignable: you cannot assign some array a2 to another a1 by the trivial assignment a1 = a2;. And C arrays decay into pointers when passed to a funtion/method.

However, the prefered way to do it in C++ is to use std::array:

#include <utility>
#include <array>

using IntArr6 = std::array<int, 6>;
IntArr6 x{ 1,2,3,4,5,6 };
IntArr6 y{ 11,22,33,44,55,66 };
std::pair<IntArr6, IntArr6> aa{ x,y };

Note the usage of using (providing a type alias) to make the code more readable (as commented @RemyLebeau).

wohlstad
  • 12,661
  • 10
  • 26
  • 39