views:

477

answers:

4

I understand that memberwise assignment of arrays is not supported, such that the following will not work:

int num1[3] = {1,2,3};
int num2[3];
num2 = num1; // "error: invalid array assignment"

I just accepted this as fact, figuring that the aim of the language is to provide an open-ended framework, and let the user decide how to implement something such as the copying of an array.

However, the following does work:

struct myStruct {int num[3];};
myStruct struct1={{1,2,3}};
myStruct struct2;
struct2 = struct1;

The array num[3] is member-wise assigned from its instance in struct1, into its instance in struct2.

Why is member-wise assignment of arrays supported for structs, but not in general?

edit: Roger Pate's comment in the thread std::string in struct - Copy/assignment issues? seems to point in the general direction of the answer, but I don't know enough to confirm it myself.

edit 2: Many excellent responses. I choose Luther Blissett's because I was mostly wondering about the philosophical or historical rationale behind the behavior, but James McNellis's reference to the related spec documentation was useful as well.

+4  A: 

In this link: http://www2.research.att.com/~bs/bs_faq2.html there's a section on array assignment:

The two fundamental problems with arrays are that

  • an array doesn't know its own size
  • the name of an array converts to a pointer to its first element at the slightest provocation

And I think this is the fundamental difference between arrays and structs. An array variable is a low level data element with limited self knowledge. Fundamentally, its a chunk of memory and a way to index into it.

So, the compiler can't tell the difference between int a[10] and int b[20].

Structs, however, do not have the same ambiguity.

Scott Turley
That page talks about passing arrays to functions (which cannot be done, so it's just a pointer, which is what he means when he says it loses its size). That has nothing to do with assigning arrays to arrays. And no, an array variable isn't just "really" a pointer to the first element, it's an array. Arrays are not pointers.
GMan
Thanks for the comment, but when I read that section of the article he says up front that arrays do not know its own size, then uses an example where arrays are passed as arguments to illustrate that fact. So, when arrays are passes as arguments, did they lose the information about their size, or did they never have the information to begin with. I assumed the latter.
Scott Turley
+14  A: 

Concerning the assignment operators, the C++ standard says the following (C++03 §5.17/1):

There are several assignment operators... all require a modifiable lvalue as their left operand

An array is not a modifiable lvalue.

However, assignment to a class type object is defined specially (§5.17/4):

Assignment to objects of a class is defined by the copy assignment operator.

So, we look to see what the implicitly-declared copy assignment operator for a class does (§12.8/13):

The implicitly-defined copy assignment operator for class X performs memberwise assignment of its subobjects. ... Each subobject is assigned in the manner appropriate to its type:
...
-- if the subobject is an array, each element is assigned, in the manner appropriate to the element type
...

So, for a class type object, arrays are copied correctly. Note that if you provide a user-declared copy assignment operator, you cannot take advantage of this, and you'll have to copy the array element-by-element.


The reasoning is similar in C (C99 §6.5.16/2):

An assignment operator shall have a modifiable lvalue as its left operand.

And §6.3.2.1/1:

A modifiable lvalue is an lvalue that does not have array type... [other constraints follow]

In C, assignment is much simpler than in C++ (§6.5.16.1/2):

In simple assignment (=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.

For assignment of struct-type objects, the left and right operands must have the same type, so the value of the right operand is simply copied into the left operand.

James McNellis
Why are arrays immutable? Or rather, why isn't assignment defined specially for arrays like it is when it's in a class-type?
GMan
@GMan: That's the more interesting question, isn't it. For C++ the answer is probably "because that's how it is in C," and for C, I'd guess it's just due to how the language evolved (i.e., the reason is historical, not technical), but I wasn't alive when most of that took place, so I'll leave it to someone more knowledgeable to answer that part :-P (FWIW, I can't find anything in the C90 or C99 rationale documents).
James McNellis
Does anyone know where the definition of "modifiable lvalue" is in the C++03 standard? It _should_ be in §3.10. The index says it is defined on that page, but it's not. The (non-normative) note at §8.3.4/5 says "Objects of array types cannot be modified, see 3.10," but §3.10 does not once use the word "array."
James McNellis
@James: I was just doing the same. It seems to refer to a removed definition. And yea, I've always wanted to know the real reason behind it all, but it seems a mystery. I've heard things like "prevent people from being inefficient by accidentally assigning arrays", but that's ridiculous.
GMan
@GMan, James: There recently was a discussion on comp.lang.c++ http://groups.google.com/group/comp.lang.c++/browse_frm/thread/feeed9c057be0d41# if you missed it and are still interested. Apparently it's not because an array isn't a modifiable lvalue (an array certainly is an lvalue and all non-const lvalues are modifiable), but because `=` requires an *rvalue* on the *RHS* and an array can't be an *rvalue*! The lvalue-to-rvalue conversion is forbidden for arrays, replaced with lvalue-to-pointer. `static_cast` isn't any better at making an rvalue because it's defined in the same terms.
Potatoswatter
@Potatoswatter: Thanks a lot for the link (I don't usually check comp.lang.c++, since most of the interesting discussion is on .moderated and comp.std.c++). That makes a lot of sense and is quite clearly stated in 4.1/1.
James McNellis
+16  A: 

Here's my take on it:

The Development of the C Language offers some insight in the evolution of the array type in C:

I'll try to outline the array thing:

C's forerunners B and BCPL had no distinct array type, a declaration like:

auto V[10] (B)
or 
let V = vec 10 (BCPL)

would declare V to be a (untyped) pointer which is initialized to point to an unused region of 10 "words" of memory. B already used * for pointer dereferencing and had the [] short hand notation, *(V+i) meant V[i], just as in C/C++ today. However, V is not an array, it is still a pointer which has to point to some memory. This caused trouble when Dennis Ritchie tried to extend B with struct types. He wanted arrays to be part of the structs, like in C today:

struct {
    int inumber;
    char name[14];
};

But with the B,BCPL concept of arrays as pointers, this would have required the name field to contain a pointer which had to be initialized at runtime to a memory region of 14 bytes within the struct. The initialization/layout problem was eventually solved by giving arrays a special treatment: The compiler would track the location of arrays in structures, on the stack etc. without actually requiring the pointer to the data to materialize, except in expressions which involve the arrays. This treatment allowed almost all B code to still run and is the source of the "arrays convert to pointer if you look at them" rule. It is a compatiblity hack, which turned out to be very handy, because it allowed arrays of open size etc.

And here's my guess why array can't be assigned: Since arrays were pointers in B, you could simply write:

auto V[10];
V=V+5;

to rebase an "array". This was now meaningless, because the base of an array variable was not a lvalue anymore. So this assigment was disallowed, which helped to catch the few programs that did this rebasing on declared arrays. And then this notion stuck: As arrays were never designed to be first class citized of the C type system, they were mostly treated as special beasts which become pointer if you use them. And from a certain point of view (which ignores that C-arrays are a botched hack), disallowing array assignment still makes some sense: An open array or an array function parameter is treated as a pointer without size information. The compiler doesn't have the information to generate an array assignment for them and the pointer assignment was required for compatibility reasons. Introducing array assignment for the declared arrays would have introduced bugs though spurious assigments (is a=b a pointer assignment or an elementwise copy?) and other trouble (how do you pass an array by value?) without actually solving a problem - just make everything explicit with memcpy!

/* Example how array assignment void make things even weirder in C/C++, 
   if we don't want to break existing code.
   It's actually better to leave things as they are...
*/
typedef int vec[3];

void f(vec a, vec b) 
{
    vec x,y; 
    a=b; // pointer assignment
    x=y; // NEW! element-wise assignment
    a=x; // pointer assignment
    x=a; // NEW! element-wise assignment
}

This didn't change when a revision of C in 1978 added struct assignment ( http://cm.bell-labs.com/cm/cs/who/dmr/cchanges.pdf ). Even though records were distinct types in C, it was not possible to assign them in early K&R C. You had to copy them member-wise with memcpy and you could pass only pointers to them as function parameters. Assigment (and parameter passing) was now simply defined as the memcpy of the struct's raw memory and since this couldn't break exsisting code it was readily adpoted. As a unintended side effect, this implicitly introduced some kind of array assignment, but this happended somewhere inside a structure, so this couldn't really introduce problems with the way arrays were used.

Luther Blissett
Sounds very reasonable!
Philipp
A: 

I know, everyone who answered are experts in C/C++. But I thought, this is the primary reason.

num2 = num1;

Here you are trying to change the base address of the array, which is not permissible.

and of course, struct2 = struct1;

Here, object struct1 is assigned to another object.

And assigning structs will eventually assign the array member, which begs the exact same question. Why is one allowed and not the other, when it's an array in both situations?
GMan
Agreed. But the first one is prevented by the compiler (num2=num1). The second one is not prevented by the compiler. That makes a huge difference.