PreIncrement and PostIncrement Behavior in C and Java

I run the following programs in Visual C ++ and Java:

Visual C ++

void main() { int i = 1, j; j = i++ + i++ + ++i; printf("%d\n",j); } 

Output:

 6 

Java:

 public class Increment { public static void main(String[] args) { int i = 1, j; j = i++ + i++ + ++i; System.out.println(j); } } 

Output:

 7 

Why is the conclusion in these two languages ​​different? How do both langauges relate to pre and postincrement differently?

+6
source share
2 answers

In C / C ++, the behavior is undefined because in this expression i changes more than once without an intermediate point in the sequence. read: What is the value of i ++ + i ++?

In a Java behavior course, these kinds of codes are clearly defined. Below is my answer for Java, step by step:

At the beginning of i there is 1 .

 j = i++ + i++ + ++i; // first step, post increment j = i++ + i++ + ++i; // ^^^ j = 1 + i++ + ++i; // now, i is 2, and another post increment: j = i++ + i++ + ++i; // ^^^^^^^^^ j = 1 + 2 + ++i; // now, i is 3 and we have a pre increment: j = i++ + i++ + ++i; // ^^^^^^^^^^^^^^^^ j = 1 + 2 + 4; j = 7; 
+2
source

The C ++ example invokes undefined behavior. You must not change the value more than once in an expression. between points in a sequence. [Edited to be more precise.]

I am not sure if this is true for Java. But this is certainly true for C ++.

Here is a good link:
Undefined behavior and sequence points

+4
source

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


All Articles