Thread: why does this give an lvalue error?

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    5

    why does this give an lvalue error?

    int a,b;

    a++ = b++;

    according to me, this is equivalent to:-
    a = b;
    b++;
    a++;
    But I get an "lvalue required error". WHY?

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    ISO 9989:1999 standard, 6.3.2.1:2:

    Except when it is the operand of the sizeof operator, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue). If the lvalue has qualified type, the value has the unqualified version of the type of the lvalue; otherwise, the value has the type of the lvalue. If the lvalue has an incomplete type and does not have array type, the behavior is undefined.

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    62
    The ++ operator evaluates to the value of its argument, not the argument itself. If a=1 and b=2, then it's like saying something roughly equivalent to this.

    Code:
    1 = 2; a = a + 1; b = b + 1;
    As 1 is not an lvalue (an lvalue is anything that would be valid on the left hand side of an assignment expression), you're getting an lvalue error. It's also bad practice to put more than one ++ or -- in an expression. There are rules to determine which one occurs first, but there is also undefined behavior in some cases (a = b++ + b++, for example) and it's best to just avoid the whole thing and only use one, or better yet, no ++ or -- operators in expressions.

  4. #4
    Registered User
    Join Date
    Apr 2019
    Posts
    5
    Thanks gaxio and flp1969 -
    that was quite instructive.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. error: lvalue required, pretty sure it's an lvalue
    By brandones in forum C Programming
    Replies: 18
    Last Post: 08-22-2011, 08:06 PM
  2. lvalue error
    By roaan in forum C Programming
    Replies: 6
    Last Post: 08-13-2009, 10:09 PM
  3. non-lvalue error
    By zlb12 in forum C Programming
    Replies: 1
    Last Post: 04-17-2009, 10:43 AM
  4. lvalue error
    By paperbox005 in forum C Programming
    Replies: 4
    Last Post: 04-10-2005, 12:18 AM

Tags for this Thread