count++ & infinite loop

Started by
13 comments, last by dimitri.adamou 11 years, 8 months ago

The result of the expression 'count++' is the value of count before incrementing it (0). So a repeated 'count = count++' is basically the same as saying 'count = 0'.
'count = ++count' would give the expected result, although there is no point in assigning count's value to itself.


no its not. True, you assigning it 0 but then you increment it by 1.
Advertisement
The problem is as stated above, the semicolon. You need to take that out. It's also good practice to add brackets after the for statement even if there is only one statement. What your code is doing is looping your entire for, and then printing out the result.

For example:


For (i=0;i<5;i++)
{
System.out.print("test: " + i);
}

no its not. True, you assigning it 0 but then you increment it by 1.


The typical implementation of a post increment would look like this:

tmp = count;
count = count + 1;
return tmp;

So no, you're not assigning first and then increment, you store the original value, then increment and the actual assignment is a completely different operator that happens last. In fact, one might argue that any compiler optimizing this code in a way that behaves the way you expect could be considered broken. You can't interrupt one operator (++) halfway through to squeeze in a different operator (=) and then go back to finish the first one.
f@dzhttp://festini.device-zero.de

no its not. True, you assigning it 0 but then you increment it by 1.

In Java, both sides of a non-short circuit binary operator are fully evaluated, including side effects, before the operator is applied. In this case it means that count is incremented before assignment occurs, not after.

[quote name='dimitri.adamou' timestamp='1345117054' post='4970116']
no its not. True, you assigning it 0 but then you increment it by 1.

In Java, both sides of a non-short circuit binary operator are fully evaluated, including side effects, before the operator is applied. In this case it means that count is incremented before assignment occurs, not after.
[/quote]

thank you that makes more sense.

This topic is closed to new replies.

Advertisement