1

Why we can initialize array with

int a[]={1,2,3};

but we can't assign data to existing array

a = {2,3,4};

?

Is it possible to make a function that takes const array as a parameter, and call it to assign variable in one line?

pseudocode:

int a[] = {1,2,3};
myfunc(a, (int){2,3,4});

void myfunc(int &array1, const int array2)
{
    copy(array2,array1);
}
2
  • The array is considered as a constant pointer and the constants are not assignable Commented Apr 6, 2020 at 21:02
  • @asmmo That's not really true. Arrays are neither [inherently] constant, nor [ever] pointers. Commented Apr 6, 2020 at 21:53

2 Answers 2

2

Since C-array can't do that. C-array doesn't have assignment operator available. Reason is purely historical. First of all memory at that time was very limited. Creating a feature to easy copy of array was considered as a waist of memory and time so it was not a priority. In fact it was more important to ensure that arrays are passed by pointer (not by value), that is why array in C and C++ decay to pointer to value. Also most of other languages of that time didn't had such capability. Later the backward comparability took over and such feature was never introduced.

Use more modern std::array where this is possible.

    std::array<int, 4> a { 1, 3, 4, -2 };
    a = { -4, -2, 0, 0 };

https://wandbox.org/permlink/PLeISvwWd8WtfZ3L

Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't really answer why, though. C++ could have had it, and why doesn't C have it?
1

Yes, you can write a function-template that deduces the size of the arrays

template<size_t N>
void myfunc(int (&a)[N], int const (&b)[N])
{
  std::copy(b, b + N, a);
}

Note that this allows the second parameter to be deduced from a brace-init list as you want. An additional advantage is that you can't get the sizes wrong.

Now you can copy in a single line

int main()
{
  int a[] = {1,2,3};

  for (auto i : a)
    std::cout << i;  // 1 2 3 

  myfunc(a, {2,3,4});

  for (auto i : a)
    std::cout << i;  // 2 3 4


  myfunc(a, {2,3,4,5});  // error, as it should be
}

2 Comments

Is it possible to auto-resize array to different number of values?
No. The size of an array is part of its type. It must be known at compile time, and cannot be changed for the duration of the program.