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
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.
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++;
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);
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.
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.
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