0

Can anyone explain to me why the following code:

#include <iostream>
using namespace std;
int main() {
    int y=3;
    int z = (--y) + (y=10);
    printf("%d \n", z);
}

prints out z=20? I thought it should be z=19 instead?

Quang Thinh Ha
  • 239
  • 2
  • 10
  • Why did you think that it should be 19? – Slava Feb 18 '21 at 18:34
  • 2
    Just to clarify the points made in the duplicate: there is nothing in the C++ Standard that determines whether `(--y)` or `(y=10)` should be evaluated first. – Adrian Mole Feb 18 '21 at 18:35
  • 1
    I could not understand how this code works but this code not depends on initial y value. Always gives the 2y(y is the last y value) – Ogün Birinci Feb 18 '21 at 18:35
  • @OgünBirinci you do not understand how it works simply because it does not work. – Slava Feb 18 '21 at 18:36
  • @slava What do you mean by `it does not work'? As in, the code wouldn't compile? Cause I tried and it did. – Quang Thinh Ha Feb 18 '21 at 18:37
  • 1
    @QuangThinhHa unfortunately in C++ the fact that code compiles does not mean it is legal. Read about Undefined Behavior https://en.cppreference.com/w/cpp/language/ub and worst thing that happens with UB - you get result you expected – Slava Feb 18 '21 at 18:39
  • 1
    @Slava You're right. Is there any specific logic in the output we get. Why we always get 2y result? Is it a random output?. Thank you for your feedback. – Ogün Birinci Feb 18 '21 at 18:41
  • 2
    @OgünBirinci it is quite pointless to discuss why you get particular value when result is garbage. If you are interested you can look into produced assembly, but again it is pointless. – Slava Feb 18 '21 at 18:43
  • 2
    @OgünBirinci Try `int z = (--y) + (--y);`, maybe that will make the situation clearer. The prefix `--` is equivalent to `y-=1`, and per [specification](https://en.cppreference.com/w/cpp/language/operator_assignment) the return value is an **an lvalue identifying the left operand after modification**. I think understanding this is the key to your confusion. See [this question](https://stackoverflow.com/q/19244627/1092820) for a neat example. – Ruzihm Feb 18 '21 at 19:07

0 Answers0