0

I am reading TCPPPL by Stroustrup. In the topic "Array", I found this:

char v4[3]={'a', 'b', 0};

Then it mentions that "there is no array assignment to match the initialization",i.e. the following gives an error:

void f()
{
v4={'c','d',0}; //error: no array assignment
}

What does the author mean here? Does he mean that after initializing the array you can't re-assign it?

1
  • 1
    Have you tried compiling and running the code? Commented May 22, 2018 at 15:10

3 Answers 3

4

Does he mean that after initializing the array you can't re-assign it?

Yes. You cannot change "the array" that an array contains. You can change the values of each element in the array but you cannot assign an array to another array.

int a[] = {1,2,3};
int b[] = {4,5,6};
b = a; // this is also illegal

This is one reason to use standard containers like std::string, std::array, and std::vector. They are assignable and copyable (and moveable).

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

Comments

1

What does the author mean here? Does he mean that after initializing the array you can't re-assign it?

Yes, that's correct. Although, you cannot assign an array before initializing it either, so that should be simplified to: "You cannot assign an array".

Comments

1

Just one interesting thing to note in addition to existing answers. Clause 11.4.5 of C++ standard points out:

The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy/move assignment of its subobjects... and if the subobject is an array, each element is assigned, in the manner appropriate to the element type."

So the following code is absolutely valid.

struct { int c[3]; } s1, s2 = {3, 4, 5}; 
s1 = s2;

Comments

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.