Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array assignment operation doesn't exist but structure assignment does in C language?

Tags:

arrays

c

int a[10];
int b[10];

a = b; // illegal

typedef struct {
    int real;
    int imag;
    } complex;

complex c,d;
c = d; //legal

[I realize that a and b are addresses in 1st case,but symbols in 2nd case]

like image 655
Hari Avatar asked Jan 20 '12 09:01

Hari


People also ask

Can we use assignment operator for array?

In C++ the equality test == may be applied to arrays, but the assignment operator = cannot be applied to arrays.

Can we use assignment operator in array in C?

C style arrays like int a[5] can't be copied by assignment operator. This style is discouraged.

What does the assignment operator do on arrays?

The assignment operator function returns a reference to the ``current'' Array. We could return a copy of the values in the array, but copying the values can take a lot of time and memory, so it is often better to return a reference to the array.

Can we copy an array using the assignment operator justify your answer?

Arrays are not assignable. You cannot use an array type variable as LHS operand of assignment operator. An assignment operator shall have a modifiable lvalue as its left operand.


1 Answers

For historical info, this may be interesting: http://cm.bell-labs.com/who/dmr/chist.html

In B, declaring an array would set aside memory for the array, just as C does, but the name supplied for the variable was used to define a pointer to the array. Ritchie changed this in C, so that the name "is" the array but can decay to a pointer when used:

The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

This invention enabled most existing B code to continue to work, despite the underlying shift in the language's semantics. The few programs that assigned new values to an array name to adjust its origin—possible in B and BCPL, meaningless in C—were easily repaired.

If at that very early stage, Ritchie had defined a = b to copy the array, then the code he was trying to port from B to C would not have been as easily repaired. As he defined it, that code would give an error, and he could fix it. If he'd made C copy the array, then he would have silently changed the meaning of the code to copy the array rather than reseating the name being used to access an array.

There's still the question, "why hasn't this feature been added in the 40 years since", but I think that's why it wasn't there to start with. It would have been effort to implement, and that effort would actually have made that early version of C worse, in the sense of being slightly harder to port B and BCPL code to C. So of course Ritchie didn't do it.

like image 141
Steve Jessop Avatar answered Oct 25 '22 22:10

Steve Jessop