Strange behavior of increment operators in Java?

I have some code snippets:

int m = 4; int result = 3 * (++m); 

and

 int m = 4; int result = 3 * (m++); 

After execution, m is 5, and the result in the first case is 15, but in the second case m is also 5, but the result is 12. Why is this? Shouldn't that be at least the same behavior?

I specifically talk about priority rules. I always thought that these rules state that parentheses take precedence over unary operators. So why is the first expression in parentheses not evaluated first?

+1
source share
4 answers

No - because in the first case the result is 3 times “the value of m after it increases”, while in the second case, the result is multiplied by “the initial value of m before it increases”.

This is the normal difference between the pre-increment ("increment" and the value of the expression — the value after the increment) and the post-increment ("remember the original value, then increase, the value of the expression is the original").

+7
source

The difference is when the result is assigned to m. In the first case, you have basically (not what it really does, but helps to understand) ...

 int result = 3 * (m=m+1); 

In the second case, you have

 int result = 3 * m; m = m +1; 
+3
source

Think of it as "increment and receive" and "receive and increase." For example, see AtomicInteger , which has the incrementAndGet () and getAndIncrement () methods.

+1
source

This is the definition of operators: m++ evaluates to m and then increments m . This is a post-increment. The brackets around it do not change the fact that the operator evaluates this variable, and also increases it subsequently.

+1
source

Source: https://habr.com/ru/post/1395016/


All Articles