15 July, 2011

Case study: Lvalue error

Try the below programs and analyse the output.

A)
int main()
{
int n = 5;
int j;

j = ++n++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

B)
int main()
{
int n = 5;
int *p = &n;
int j;

j = ++*p++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

C)
int main()
{
int n = 5;
int *p = &n;
int j;

j = ++(*p)++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

PS: First of all, U need to know operator precedence and associativity to understand the program.

1 comment:

  1. Guys finally I have got some references to the explanation of lvalue error related to increment operators. "Its a piece-of-cake!!!"
    Check out the below link:
    http://stackoverflow.com/questions/371503/why-is-i-considered-an-l-value-but-i-is-not

    Also here is the brief explanation of lvalue and rvalue from wiki:
    http://en.wikipedia.org/wiki/Value_%28computer_science%29

    Conclusion (as I understood):
    lvalue is an expression referring to an object (considered as representing an object ‘‘locator value’’), whereas rvalue is "value of expression".
    Each operator specifies whether it expects lvalue operands and whether it yields an lvalue.
    Thus n++ or (*p)++ yields a rvalue which cannot be modified by pre-increment operator as it expects a lvalue (modifiable) operand. Whereas the *p++ still yields a lvalue which is happily accepted by pre-increment operator. So ++*p++ works!!! but neither ++(*p)++ nor ++n++.
    PS: Figuring out the difference between ++*p++ and ++(*p)++ is left as an exercise for you KIDS!!

    ReplyDelete