Can an array be an lvalue?

Posted on:
tags: , , , , , , , ,

Can an array be an lvalue?


Answer:


In FAQ I.9, an lvalue was defined as an expression to which a value can be assigned. Is an array an expression to which we can assign a value? The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes. The following statement is therefore illegal:

int x[5], y[5];
x = y;
You could, however, use a for loop to iterate through each element of the array and assign values individually, such as in this example:
int i;
int x[5];
int y[5];

...
for (i=0; i<5; i++)
x[i] = y[i]
...

Additionally, you might want to copy the whole array all at once. You can do so using a library function such as the memcpy() function, which is shown here:

memcpy(x, y, sizeof(y));

It should be noted here that unlike arrays, structures can be treated as lvalues. Thus, you can assign one structure variable to another structure variable of the same type, such as this:

typedef struct t_name
{
char last_name[25];
char first_name[15];
char middle_init[2];
} NAME;
...
NAME my_name, your_name;
...
your_name = my_name;
...


In the preceding example, the entire contents of the my_name structure were copied into the your_name structure. This is essentially the same as the following line:

memcpy(your_name, my_name, sizeof(your_name));

Cross Reference:


---------------------------------------------------------------------------------
Posted By Sundeep aka SunTechie

Sundeep is a Founder of Youth Talent Auzzar, a passionate blogger, a programmer, a developer, CISE and these days he is pursuing his graduation in Engineering with Computer Science dept.
Add Sundeep as a Friend on 


No comments:

Post a Comment

< >