Why is the result 8 and not 9?
By my logic:
++x
gives 4x = 8
x
should be increased due to x++
, so it should be 9.What's wrong with my logic?:
int x = 3;
x = x++ + ++x;
System.out.println(x); // Result: 8
Increment in java is performed in two ways, 1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
In C/C++, Increment operators are used to increase the value of a variable by 1. This operator is represented by the ++ symbol. The increment operator can either increase the value of the variable by 1 before assigning it to the variable or can increase the value of the variable by 1 after assigning the variable.
scoreTeamB++ returns the previous value of the variable (before it was incremented). += returns the value that was assigned to the variable.
a++ vs. Popular languages, like C, C++ and Java, have increment ++ and decrement -- operators that allow you to increment and decrement variable values. To increment a value, you can do a++ (post-increment) or ++a (pre-increment): int a = 1; a++; printf("%d", a); // prints 2.
You should note that the expression is evaluated from the left to the right :
First x++
increments x but returns the previous value of 3.
Then ++x
increments x and returns the new value of 5 (after two increments).
x = x++ + ++x;
3 + 5 = 8
However, even if you changed the expression to
x = ++x + x++;
you would still get 8
x = ++x + x++
4 + 4 = 8
This time, the second increment of x (x++
) is overwritten once the result of the addition is assigned to x.
++x is called preincrement and x++ is called postincrement. x++ gives the previous value and ++x gives the new value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With