Hans Geuns-Meyer wrote:
> So, what was fishy in this code -- except for my typo in the second for-loop -- was 
>the assignment
> 
> i = i--
> 
> The correct version of the first for-loop would simply have had "i--" or "--i", 
>instead of "i=i--".
> 
> If you have an assignment j = i--, it's clear what's going to happen: j gets the 
>value of i, and
> after that i is decremented. In this case it's not so clear what is supposed to 
>happen.  In C (or
> C++), if i==n, then after executing i=i--, i turns out to have the value n-1. The 
>funny thing is
> that in Java i will still have the value n.
> 
> I am tempted to think that C does it right and Java does it wrong, so I'm tempted to 
>see this as a
> bug in the Java language (I also wonder if all compilers produce the same code).  
>The Java language
> specification does not seem to specify unambiguously how i=i-- should be interpreted.
> (http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#39438)

Section 15.7.1 "Evaluate Left-Hand Operand First" of the Java language 
spec. specifies that the behavior we see is correct.

The bottom line, of course, is that the code "i = i--" is a bug, and we 
shouldn't write it that way.  If you see broken code on the final exam, 
ask for clarification.

-- 
Richard Kasperowski (mailto:[EMAIL PROTECTED])
Tel: 617-576-1552, Fax: 617-576-2441
http://www.altisimo.com/


Reply via email to