3 ms·
Adding side effects to your array index expression and depending on order of their evaluation is a bad idea anyway. Unfortunately, the `++` / `--` made it to J
by nine_k 8y ago
Adding side effects to your array index expression and depending on order of their evaluation is a bad idea anyway.
Unfortunately, the `++` / `--` made it to Java, and are still used sometimes, despite JVM not being PDP-11, and definitely not trying to conserve every precious byte of RAM.
- wrs 8y agoApparently it’s nothing specific about arrays or ++ — any expression on the left hand side of the compound operator is evaluated twice, so any side effects happen twice.
- nine_k 8y agoIf you read the original post to the end, you'll notice a piece of code that seemingly refutes this statement. That is, in case of Java 8, the index expression is evaluated once. and in case of Java 9, twice.
- Dylan16807 8y agoWhat does that refute? You seem to be agreeing with the post you're replying to. But importantly your original point about "depending on order of their evaluation" is wrong. Most of the examples don't care about order at all. They break because things happen the wrong number of times.
- asdsa5325 8y agoRead his comment again.
- kjeetgill 8y agoIt's worth noting: the bug in question only occurs when it's an array of String[]. Strings are a special case for just about everything in the compiler. :(
- cesarb 8y agoUnlike in C or C++, the order of evaluation in Java is well defined, so there's no problem depending on it.
- chopin 8y agoDo you have a reference for this? If I remember correctly the Java spec says nothing definite about evaluation order and the memory model mentions reordering explicitely ("happens before" relationships rely on a memory barrier; without that, no guarantees).
- cesarb 8y agoJust open the Java Language Specification and look at the table of contents: chapter 15.7 is titled "Evaluation Order" and specifies it in detail.
- chopin 8y agoThanks. What I had in mind applies to distinct statements not expressions. Funnily the chapter starts with the following caveat: It is recommended that code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.
- MBCook 8y agoThey’re not depending on the order of evaluation, but the rule that the evaluation of the expression on the LHS should only happen once.