In this code:
int y = 10; int z = (++y * (y++ + 5));
What I expected
First y++ + 5
will be executed because of the precedence of the innermost parentheses. So value of y
will be 11 and the value of this expression will be 15. Then ++y * ()
will be executed. So 12 * 15 = 180. So z=180
What I got
z=176
This means that the VM is going from left to right not following operator precedence. So is my understanding of operator precedence wrong?
When two operators share an operand and the operators have the same precedence, then the expression is evaluated according to the associativity of the operators. For example, since the ** operator has right-to-left associativity, a ** b ** c is treated as a ** (b ** c) .
All comparison operators have equal precedence, and all have greater precedence than the logical and bitwise operators, but lower precedence than the arithmetic and concatenation operators.
Operator Precedence ¶ The precedence of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3 , the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.
If consecutive operators in an expression have the same precedence, a rule called associativity is used to decide the order in which those operators are evaluated.
The expression (++y * (y++ + 5)); will be placed in a stack something like this:
1. [++y] 2. [operation: *] 3. [y++ + 5] // grouped because of the parenthesis
And it will be executed in that order, as result
1. 10+1 = [11] // y incremented 2. [operation: *] 3. 11+5 = [16] // y will only increment after this operation
The the expression is evaluated as
11 * 16 = 176
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