Search code examples
c++compiler-errorslvaluepre-incrementoperands

C++ Help: Error: lvalue required as increment operand


What is wrong here. What does it mean by the error: lvalue required as increment operand? (NOTE: this is a textbook example)

    #include <iostream>
    using namespace std;

   int main()
  {
    int num1 = 0, num2 = 10, result;
    
    num1++;
    
    result = ++(num1 + num2);
    
    cout << num1 << " " << num2 << " " << result;

    return 0;
}

Solution

  • The ++x is called preincrement operator while x++ is called postincrement. Both need a modifiable 'lvalue' variable as the operand. In this case x is the 'lvalue'.

    If you have a code y = ++x it has the same semantic meaning as

    x = x + 1;
    y = x;
    

    So this specific code ++(num1 + num2) is actually making the error because num1 + num2 is not a valid modifiable variable and the semantic of result = ++(num1 + num2) will be:

    num1 + num2 = (num1 + num2) + 1; // this is invalid
    result = num1 + num2;
    

    You can fix it as:

    int x = num1 + num2;
    result = ++x;
    

    Or the shorter version, that produces the same result:

    ++(result = num1 + num2)