Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the operator precedence not followed here? [duplicate]

Tags:

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?

like image 807
EdmDroid Avatar asked Mar 20 '15 08:03

EdmDroid


People also ask

What happens when two operators have the same precedence?

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) .

Do all comparison operators have the same precedence?

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.

What is the precedence of 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.

What decides the order in which the operator with the same precedence are executed?

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.


1 Answers

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 
like image 112
owenrb Avatar answered Sep 23 '22 00:09

owenrb