Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of PreIncrement and PostIncrement operator in C and Java [duplicate]

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?

like image 403
Jainendra Avatar asked Jul 07 '13 18:07

Jainendra


People also ask

What is the difference between Preincrement and Postincrement in Java?

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.

What is the difference between Preincrement and Postincrement in C?

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.

What is Preincrement in C?

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.

Is i ++ and ++ i the same thing?

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.


1 Answers

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

like image 113
Joe Z Avatar answered Sep 30 '22 12:09

Joe Z