Attyuttam Saha January 2017

why does if(++x=++y) works and if(x++=++y) does not work?

when i am executing this program:

#include<iostream>
using namespace std;
int main(){
    int x=5,y=9;

    if(++x=y++){
        cout<<"Works "<<x;
    }
    else{
        cout<<"No";
    }
    return 0;
}

it works fine and the output is: Works 9

but if i execute:

  #include<iostream>
using namespace std;
int main(){
    int x=5,y=9;

    if(x++=y++){
        cout<<"Works "<<x;
    }
    else{
        cout<<"No";
    }
    return 0;
}

it states: In function 'int main()': 6:11: error: lvalue required as left operand of assignment if(x++=y++){

Answers


BoBTFish January 2017

Because x++ isn't an lvalue.

More specifically, x++ increments x, then returns a temporary with the original value of x. A temporary object can't (casts of dubious legality aside) be used on the left hand side of an assignment, so it is not an lvalue.

++x increments x and returns a reference to x (with its new value). You can then assign directly to it if you choose, so it is an lvalue.

However, it is possible you actually meant to compare the two expressions for equality, rather than do an assignment. In which case, you need to use == rather than =.


Victor Tran January 2017

x++ returns x, and then increments x. On the other hand, ++x increments x, and then returns it.

The second case makes sense; x is being returned, and you can do whatever. The first case makes no sense at all; x++ isn't a value. In fact, once you get back the value, x is no longer that value.


Joachim Pileborg January 2017

You have to remember that the suffix increment operator returns the old value, before the increment.

This value is a very temporary value, and as all other temporary values it is not an "lvalue", i.e. it is not something that can be assigned to.

The prefix increment operator does its increment operation, and then return a reference to the new value. For ++x it returns a reference to x. It is an "lvalue".

The same of course goes for the decrement (--) operator.

There are many sources all over the Internet that will help you understand the difference between "lvalues" and "rvalues" (temporaries).


salhernandez January 2017

This happens because in the second code snippet you are assigning a value, and not comparing them.

A = B  //assigns value B to A
A == B //compares values A and B

Post Status

Asked in January 2017
Viewed 1,834 times
Voted 12
Answered 4 times

Search




Leave an answer