Jin Jin - 2 months ago 10x
C Question

Is there a reason why array name is not a lvalue?

For example,

int x[10];
int i = 0;
x = &i; //error occurs!

According to C - A Reference Manual, it says that array name cannot be lvalue. Thus, x cannot be a lvalue. But I'm curious of the reason behind the fact that array name cannot be lvalue! For example, why does error occur in the third line? Can anyone explain me why?


Your reference is incorrect. An array can be an lvalue (but not a modifiable lvalue).

Take your example:

int x[10];
int i = 0;
x = &i; //error occurs!

Apply C11 6.5.1, paragraph 2:

An identifier is a primary expression, provided it has been declared as designating an object (in which case it is an lvalue) ...

We see that x is a primary expression and is an lvalue, because it has previously been declared as designating an array object.

However, the C language rules state that an array expression in various contexts, including the left-hand-side of an assignment expression, are converted to a pointer which points at the first element of the array and is not an lvalue, even if the array was. Specifically:

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

(C11 paragraph 3).

The pointer which is the result of the conversion specified above is not an lvalue because an lvalue designates an object, and there is no suitable object holding the pointer value; the array object holds the elements of the array, not a pointer to those elements.

Your question (including the example) implies that you understand that an array expression decays (is converted to) a pointer value, but I think you are failing to recognize that after the conversion, the pointer value and the array are two different things. The pointer is not an lvalue; the array might be (and in your example, it is).

If you were to ask instead: Why do arrays decay to pointers when they are on the left-hand-side of an assignment operator? - then I suspect that there is no particularly good answer. C just doesn't allow assignment to arrays, historically.