I know about the prefix and posfix operation… the difference between ++i and i++ and so.
But I think I'm missing something here. Below you can find the code:
package test;
public class Test
{
public static void main (String[] args)
{
int i=0;
i+=i++;
System.out.println(i); // Prints 0
i = i + (i++);
System.out.println(i); // Prints 0
i = i + (i+1);
System.out.println(i); // Prints 1
}
}
So the output is:
0
0
1
I tried the same code in C:
#include <stdio.h>
#include <string.h>
main()
{
int i=0;
i+=i++;
printf("%d", i); // prints 1
i = i + (i++);
printf("%d", i); // prints 3
i = i + (i+1);
printf("%d", i); // prints 7
}
and the output was:
1
3
7
Why i+=i++
doesn't increment i
while the same code in C it increments the values?
Best Answer
Java
In Java, the expression has a well-defined meaning. The specification for the compound assignment operators says:
So
is equivalent to
Because the value of the left-hand side is saved at the start, and then added to the value of right hand side, and because expression evaluation in Java is left-to-right, the modification of
i
caused byi++
is overwritten by the subsequent assignment.All this means that
is equivalent to
C
In C the expression
has undefined behavior. And so anything might happen when you execute this code. Which means that you cannot predict what value
i
will have after the statement completes.And so it is entirely to be expected that the output from your C program differs from the output from your Java program.