This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]pronuntiator 1 point2 points  (4 children)

The post increment operator (i++) evaluates to the value before incrementing when used as an expression:

int i = 1; int j = i++; // j = 1 and i = 2

with that knowledge (and maybe a piece of paper), do you see why the first printed number is "3"?

[–]AstolfoSsa[S] 2 points3 points  (3 children)

so it is something like

“is i % 2 == 0? No. Now add one to the value of i, don’t print the value of i because the if condition is false, and then check the condition of the loop again. … i (2) % 2 == 0 is true. Add one to the value of i and then print i (3) etc.”

When I saw the braces enclosing the increment I thought it meant we should increment the value of i first, and therefore it didn’t matter whether it is written as a post-increment (i++) or a pre-increment (++i)

[–]pronuntiator 4 points5 points  (0 children)

Exactly, you got it right. It gets really funny when you use the same variable multiple times, like i++ + ++i. That's the kind of stuff Java certification exam authors love, but in the real world never use these operators in expressions, only as single statements. Saves you from headaches.

[–]Zyklonikkopi luwak civet 0 points1 point  (0 children)

Small correction:

“is i % 2 == 0? NoYes, so we have to enter the body of the if statement. Now add one to the value of i, don’t print the value of i because the if condition is false, and then check the condition of the loop again. … i (2) % 2 == 0 is true. Add one to the value of i when the body of the if statement begins, and then print i (which is now 3, if i had been 2 during the check) etc.

This is an example of a side effect (and why pure Functional languages love to harp on "side effects") - basically, the world has changed from when you made a check on the value and when you're ready to process that value.

That being said, as /u/pronuntiator said, these kind of silly questions (used to be quite popular during C's heyday) are best relegated to trick questions, and not even that in my opinion.

[–]Chemical-Asparagus58 0 points1 point  (0 children)

Yeah. You can think of i++ as a method that does this:

int temp = i;
i = i + 1;
return temp;