Can somebody explain for the answer??
Code:class C {
static int f1(int i) {
System.out.print(i + ",");
}
public static void main(String[] args) {
int i = 0;
i = i++ + f1(i);
System.out.println(i);
}
}
Printable View
Can somebody explain for the answer??
Code:class C {
static int f1(int i) {
System.out.print(i + ",");
}
public static void main(String[] args) {
int i = 0;
i = i++ + f1(i);
System.out.println(i);
}
}
The answer is :1,0
I've a doubt there, can you compile the code without any error. In the f1() method that return statement is missing. Based on the return value the answers are different.
There should be a return statement in that method.
// return 0;
Sorry for inconvenence!
With the post-increment operator, the current value of i is used, in that position, and then i is incremented, with the pre-increment operator i is incremented before its value is evaluated. So, a few examples.
int i = 0;
i = i++;
In the second statement i start at zero, so that value is saved to be used in the next action.
Then i is incremented, so at that point i is 1.
Then the next action is performed (in this case assignment) so i is assigned the saved value, which is 0, so i has the value 0 again.
i = ++i;
i is still 0 (continuing from last example).
i is incremented, so i is now 1.
The assignment action then assigns 1 to i, so i has the value 1.
Both examples, up to this point, display "bad" actions. Never do anything that even remotely resembles that.
i = i++ + ++i;
i has the value 1 (continued from last example), so this value is "saved".
i is incremented so i now has the value of 2.
i is incremented, again, since pre-increment increments before evaluation, so i is now 3.
The add action is performed with 1 + 3 = 4;
The assignment occurs assigning 4 to i.
So i now equals 4.
the pre and post decrement operators work the same way.
So, since your method returns 0 it goes like this
i = i++ + f1(i);
i has the value 0 so that value is "saved" to be used with the "+" action.
i is incremented, so it now has the value one.
the f1 method receives the value 1 (since i is now 1), prints it and returns 0.
The "+" action occurs doing 0 (the "saved" value) + 0 (the returned value) which equals 0.
The assignment action occurs assigning the calculated 0 from above to i, so i is 0.
Thanks for your kind explanations, both Eranga and masijade!
could please tell me the difference between C's increment operator and Java's (If any!).
Thanx n advanced!
Eseentially, there shouldn't be any difference, but C's language specs do not explicitly define the behaviour in some situations, whereas Java does, so different C compilers sometimes handle certain situations differently (such as when the next action is assignment).
Thanks a lot!
This is not a C forum, but just send you a simple code here. Try to figure it out.
Code:#include<cstdio>
int main(){
int a = 1, b = 2, c = 1, d = 0;
(a+d-c)?a++:--a = (--a)?(c--)?--d:a++:b--;
printf("%d\n",a);
}
Thanks Eranga!
You are welcome! :)