I'm running 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 the output in these two languages are different? How both the langauges treat pre and postincrement operators differently?
1) Post-Increment (i++): we use i++ in our statement if we want to use the current value, and then we want to increment the value of i by 1. 2) Pre-Increment(++i): We use ++i in our statement if we want to increment the value of i by 1 and then use it in our statement.
In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value.
1) Pre-increment operator: A pre-increment operator is used to increment the value of a variable before using it in an expression. In the Pre-Increment, value is first incremented and then used inside the expression.
The only difference is the order of operations between the increment of the variable and the value the operator returns. So basically ++i returns the value after it is incremented, while i++ return the value before it is incremented. At the end, in both cases the i will have its value incremented.
The C++ example evokes undefined behavior. You must not modify a value more than once in an expression. between sequence points. [Edited to be more precise.]
I'm not certain if the same is true for Java. But it's certainly true of C++.
Here's a good reference:
Undefined behavior and sequence points
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With