简体   繁体   中英

increment and addition operators precedence, cpp

I have 2 questions.
consider this code:

int x=1,y=2;
int z =(x++)+(++y);
int w = (++x)++;
cout << z << "\t" << w << "\t" << x;

Now, this gives me 4, 3 and 4 and I'm guessing that w=3 is because this int w = (++x)++ is undefined behavior, and that's fine with me. What I don't understand is this: I tried to write this line int w = (++x)++; like this int w = ++x++; and got error: lvalue required as increment operand , but, I saw here that postfix takes precedence over prefix, so why the isn't the postfix increment done, returns the variable and then increments it with the prefix? (as it is done when I use bracket)

Now back to this line: int z =(x++)+(++y) . I tried to write it like int z =x+++++y and that didn't work - same error. Then I tried int z =x+++(++y) and it was fine, so what I think happened is this:

  1. x++
  2. ++y
  3. addition

but if I'm correct, why the brackets were needed? this is the way it should be by precedence

so why the isn't the postfix increment done, returns the variable

The postfix version doesn't return a reference, it returns a value - and the prefix increment can only work with a reference.

By adding brackets, you've changed the order of evaluation.

It is not an issue of precedence, but the way compiler parses the code. To compile correctly you don't need to use brackets. Will work fine with spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM