Priority of unary operations

Here's an example that outputs 6

:

public static void main(String[] args) {
    int i = 1;
    m(++i);
}

static void m(int i) {
    i = ++i + i++; 
    System.out.println(i);
}

      

We get 6

, because in the beginning 3

, and 3

the method m(int i)

is added, then i

it becomes 4

(due to i++

), but after that i

the left-hand side is taken the total value 6

.

But if the method is changed to the following, we get 7

:

static void m(int i) {
    i = ++i + ++i; 
    System.out.println(i);
}

      

But I was expecting to see 7

in both cases (I was guided by the fact that unary operations, in this case incremental ones, have higher precedence than binary operations). Can anyone comment on an explanation (or link to an explanation) of the ignored i++

in the first example?

+3


source to share


3 answers


++i

increments i

and returns a new value i

.

i++

increments i

and returns the old value i

.

Expressions are evaluated from left to right, taking operator precedence into account.



So in ++i + i++

, when you start with i == 2

, you get:, ++i

which increments i

to 3

and returns 3

; then i++

, which increments i

to 4

and returns 3

. Then finally you have i = 3 + 3

, so i

it becomes 6

.

Note that these are fun tricks and have nothing to do with real world programming.

+4


source


Can anyone please provide an explanation (or link to an explanation) of the ignored i++

in the first example?

i++

is a post-affinity; it increments i

, but evaluates the value i

before incrementing. So for example:

int i = 3;
System.out.println(i++); // prints 3
// now, i == 4

      



In other words, you can think of it i++

as meaning ((i += 1) - 1)

. So in your example:

i = ++i + i++;

      

i++

at the end is not exactly ignored - it increases i

- but it is immediately replaced by the assignment.

+2


source


The increment is not ignored; it is a postincrement statement (i.e. it is applied after a link i

). Let's go through the code.

When you add (++i + i++)

it is done from left to right. This means that no matter what value i pre-increments at first (so it will take 2 to 3) then add 2. i

finished your link, so it will add 1 more, for a total of 6.

In your second example, when you add (++i + ++i)

, the value i

is entered twice twice, so you will see 3 + 4

.

+1


source







All Articles