Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post and Pre increment operators

Tags:

java

scjp

ocpjp

When i run the following example i get the output 0,2,1

class ZiggyTest2{

        static int f1(int i) {  
            System.out.print(i + ",");  
            return 0;  
        } 

        public static void main(String[] args) {  
            int i = 0;  
            int j = 0;  
            j = i++;   //After this statement j=0 i=1
            j = j + f1(j);  //After this statement j=0 i=1
            i = i++ + f1(i);  //i++ means i is now 2. The call f1(2) prints 2 but returns 0 so i=2 and j=0
            System.out.println(i);  //prints 2?
        } 
    } 

I don't understand why the output is 0,2,1 and not 0,2,2

like image 757
ziggy Avatar asked Dec 23 '11 11:12

ziggy


People also ask

What are pre increment and post increment operators?

Preincrement and Postincrement in C are the two ways to use the increment operator. 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.

What is pre and post increment with example?

Pre Increment Operation a = 11 x = 11. 2) Post-increment operator: A post-increment operator is used to increment the value of the variable after executing the expression completely in which post-increment is used. In the Post-Increment, value is first used in an expression and then incremented. Syntax: a = x++;

What is ++ i and i ++ in C?

In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. That means both i++ and ++i will be equivalent. i=5; i++; printf("%d",i);

Who is post operator?

The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one. if the expression is a = b++; and b is holding 5 at first, then a will also hold 5.


1 Answers

If we expand i = i++ + f1(i) statement, we get something like following

save the value of i in a temp variable, say temp1 // temp1 is 1
increment i by one (i++)                          // i gets the value 2
execute f1(i), save return value in, say temp2    // temp2 is 0, print 2
assign temp1 + temp2 to i                         // i becomes 1 again

I guess main steps can be summarized like above.

like image 135
melihcelik Avatar answered Oct 16 '22 13:10

melihcelik