Wednesday, May 12, 2010

Lvalue & Rvalue.

Lvalue and Rvalue discussion unwittingly took many minutes of students time in his collage days. And it bought smiles on the face of an interviewer and frown on the face of interviewee. But with such an impressive resume, a programmer does not put much thought to it once he/she get out of the collage and clears the interview. This is one topic which is comparatively hard to explain than actually put it into action. Because it comes in naturally , which is very hard thing to come by in 'C'.

The rule simply put, LV is the address of , and RV is the actual contents.

Lets see what Lvalue (LV) & Rvalue (RV) are with a simple 'C' program.

Lesson:01: This will not compile.

...
int a = 0;
/* Here 'a' is RV. And its actual contents is 0 (zero). While numerical 5 is LV (or trying to be) because what then is the address of '5'. This program will fail with "lvalue required ..." error. By this the compiler is saying that to store the contents ( RV aka 0) i need an address. With numerical 5 i am unable to get it. So i am angry and i will not proceed */
5 = a;
printf("a = %d\n",a);
...

Lesson:02: This will compile.

...
int a = 0;
/* Here 'a' is LV. And its address will be '&a'. While numerical 5 is RV and its contents is also 5. */
a = 5;
printf("a = %d\n",a);
...


Lesson:03: This will compile. This is extension of Lesson:02 to explain things better.

...
int a = 0;
int b = 5;
/* Here 'a' is LV. And its address will be '&a'. While for 'b', the compiler will take the contents which is 5 , so here 'b' is RV */
a = b;
printf("a = %d\n",a);
...


Thanks
Arshad

No comments:

Post a Comment