1

Possible Duplicate:
Why does C++ support memberwise assignment of arrays within structs, but not generally?

In C language, struct can be copied by immediate assignment but array can't.

int a[2] = {1, 2};
int a2[2] = a; /*illegal*/
int *p = a; /*assigned by reference*/

struct S {int i; int j;};
struct S s = {1, 2};
struct S s2 = s; /*assigned by value*/

What are the design advantages in C language to differentiate the assignment of array and struct?

@EDIT

In fact, we usually think of passing by value when invoking C functions like many other languages, but if the argument is of array, it's effectively passed by reference.

struct S {int i; int j;};
void pass_by_value(struct S s);
struct S s2 = {1, 2};
pass_by_value(s2); /* s2 is copied to s */

void pass_by_ref(int a[]);
int a2[] = {1, 2};
pass_by_ref(a2); /* a2 is referenced to a */

There's a syntax sugar for array pervasive in C programming:

array_var == &array_var

If we want a new language feature that array can be copied like struct by immediate assignment, the legacy code will then definitely broken. Is this one of the major obstacles to have a clonable array in C?

Community
  • 1
  • 1
sof
  • 8,243
  • 15
  • 49
  • 78
  • 1
    Technically, none of those lines you show are _assignments_, they are _initialization_. You couldn't do `int a[2]; a = { 1, 2 };` though `int a[2] = { 1, 2 };` is legal, and with `struct`s you can't do `struct S { int i; int j; } s; s = { 1, 2 };` either, though you can do `s = (struct S){ 1, 2 };` in C99. – Chris Lutz Jan 28 '12 at 21:33

2 Answers2

1

In pre-K&R C struct objects were also not assignable. When this was changed, arrays were also considered but it was noticed the C standard needed to many changes to accommodate this for arrays.

ouah
  • 138,975
  • 15
  • 262
  • 325
0

You can even do:

struct S {
   int a[2];
};

and assign them easily. So arrays can be assigned indirectly, if you wrap them in a struct.

Aaron McDaid
  • 25,518
  • 9
  • 58
  • 85