Operator Precedence

11

I have a question regarding the precedence of operators in JAVA. I have the following code:

int x = 2;
long y = 1 + x * 4 - ++x; 

Viewing the precedence table here .

In my view the expression should be resolved as follows:

1 + x * 4 - 3
1 + 3 * 4 - 3
1 + 12 - 3
y=10

Contrary to what I put in, the response given by the running program is y=6 . Would you like to know why he did the multiplication before the increment?

By the precedence table, increment in my view should be done first.

    
asked by anonymous 16.11.2015 / 23:47

3 answers

9

His error was to assume that the subexpression ++x would be evaluated before of the subexpression x * 4 . At the time this expression evaluates, x is still 2 , so the correct resolution is:

(1 + (x * 4)) - (++x)   [x=2]
(1 + (2 * 4)) - (++x)   [x=2]
(1 + 8) - (++x)         [x=2]
9 - (++x)               [x=2]
9 - x                   [x=3]
9 - 3                   [x=3]
6                       [x=3]

Operator precedence refers only to "where to put the parentheses" in the expression. The evaluation, however, occurs from left to right, just like everything else in the programming language (eg order of evaluation of the arguments of a function, order of execution of the instructions, etc.)

    
16.11.2015 / 23:54
2

Because there is also associativity that is left to right. It does not analyze all operators and chooses which one to run first. He does this with the operands, usually in pairs, from left to right in most cases. It only changes the direction when the associativity is inverse as is the case, for example, of the assignment operators.

So the multiplication is not mingling with the incracting operation, it is executed before realizing that there will be this operation.

precedence table with associativity .

The ideal is to avoid using operators that cause side effects in larger expressions, usually the increment operator is best used in isolation or when its isolation becomes clear.

    
16.11.2015 / 23:54
0

The expression is from left to right. Here's how:

int x = 2;
long y = 1 + x * 4 - ++x;
1 + 2 * 4 - ++x;
1 + 8 - ++2;
1 + 8 - 3;
9 - 3;
6
    
17.11.2015 / 01:44