How many times will the following code print "Hello World"?
D. The code will not compile because of line 3.
E. The code will not compile because of line 5.
F. The code contains an infinite loop and does not terminate.
this is my interpretation :
First iteration i is equal to 0,
i is reassigned as itself (still 0)
i is incremented by 1 (i is now 1)
Second iteration i is equal to 1,
i is reassigned as itself (still 1)
i is incremented by 1 (i is now 2)
10th iteration i is equal to 9,
i is reassigned as itself (still 9)
i is incremented by 1 (i is now 10)
: end of loop
However the correct answer is F which I cant really understand
F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments
i but then assigns i the old value. Therefore, i ends the loop with the same value
that it starts with: 0. The loop will repeat infinitely, outputting the same statement over
and over again because i remains 0 after every iteration of the loop.
Dave Tolls wrote:The post-increment operator returns the value before the increment.
So i is 0 initially, i++ will return 0, so i = i++ will reset i back to zero after the increment.
Of course it is correct, but I think this question is most difficult one to explain in some comprehensive way so the starter would understand easily.
@OP in case you didn't get what Dave explained, here, in addition to Dave's explanation, is mine one.
When you have an expression like this:
i = i++;
Post increment means, you place current i value to an expression and only then increment.
So, since i is equal to 0 at the beginning, what you get is:
i = 0;
then at some moment in time, as an intermediate step, i get's incremented to 1 for a blink of an eye, but it gets discarded (not sure I can use this wording), because the actual assignment takes place which makes i to be assigned to 0 as shown above. And the story from here repeats over and over (because you have loop).
For an interest, let's have a look what most recent IntelliJ IDEA (build 181.3741.2) give as a warn for having such code:
The value changed at 'i++' is never used.
This inspection points out the cases where a variable value is never used after its assignment, i.e.: - the variable never gets read after assignment OR - the value is always overwritten with another assignment before the next variable read OR - the variable initializer is redundant (for one of the above two reasons)