r/AskComputerScience • • Mar 11 '20

We've had quite a bit of debate inside my (Java) class on this problem. The debugger says line 7 is like a = 4 + 3 then it increments it be 1 before it assigns it however by that logic wouldn't the output be "-1"?

Post image
84 Upvotes

41 comments sorted by

175

u/sepp2k Mar 11 '20 edited Mar 11 '20

Here are the things you need to know:

  • ++a increments a and evaluates to the incremented value

  • a++ also increments a, but evaluates to the unincremented value

  • The operands of an operator are evaluated left-to-right

  • When a sub-expression is evaluated, all of its side-effects will have taken effect before the evaluation of the outer expression continues

  • In an assignment expression, the assignment happens after the evaluation of the assigned expression

So on line 7 the following things will happen in the following order:

  1. a = ++a + a++ starts being evaluated

  2. ++a + a++ starts being evaluated

  3. ++a sets the value of a to 4 and evaluates to 4

  4. a++ sets the value of a to 5 and evaluates to 4

  5. ++a + a++ is now 4 + 4 and evaluates to 8

  6. a = ++a + a++ is now a = 8 and sets a to 8

Then on line 9:

  1. a = --a - a-- starts being evaluated

  2. --a - a-- starts being evaluated

  3. --a sets the value of a to 7 and evaluates to 7

  4. a-- sets the value of a to 6 and evaluates to 7

  5. --a - a-- is now 7 - 7 and evaluates to 0

  6. a = --a - a-- is now a = 0 and sets a to 0

PS: All of this applies to Java and many other languages, but there are notable languages where the rules are different and the equivalent code would behave different or have no defined behavior at all (in C and C++ it's undefined behavior).

35

u/Triple96 Mar 11 '20

This is the correct answer. Very methodically tracing the code and keeping track of variables. Nice answer

13

u/Mukhasim Mar 11 '20

Great post.

Eric Lippert wrote an article a few years back, "Sharp Regrets: Top 10 Worst C# Features", where he said he wished that the ++ operators had been omitted from C#. He complained that few people know how they really work and even he has trouble keeping it straight in his head.

1

u/KuntaStillSingle Mar 11 '20

He complained that few people know how they really work

How much does this cause issue in practice though? Like if someone wants to run a function with i and increment it, they'd want to write it like

function(i);
i++; //++i doesn't matter

Instead of something like

function(i++); //This will work, ++i would function differently

anyway, right?

4

u/Mukhasim Mar 11 '20 edited Mar 11 '20

If you use it as a lone statement then it doesn't matter [it doesn't hurt], but then it also buys you nothing as a language feature because you could've written i += 1. Allowing increment/decrement mainly makes code more concise in the very places where makes code more confusing. In C# the situation is worse because the language supports operator overloading and programmers don't always understand the semantics of implementing ++/-- (which differs from C++).

1

u/KuntaStillSingle Mar 11 '20

it also buys you nothing as a language feature

As someone who prefers += I'll agree, but I'm not sure I'd agree if I preferred ++ lol

programmers don't always understand the semantics of implementing ++

If I understand his explanation the C# implementation looks something like:

int operator++(int &a){ //postfix
    int aVal = a; //determine the value of the variable
    
    int storVal = aVal + 1; //determine what value 
                //will be assigned back to storage
    
    a = storValue; //assign the new value to storage
    return aVal; //postfix operator returns the original value
}

And his concern is a cpp; programmer will try to overload this in a way which produces a return before it increments the value or assigns it to storage, say something like this, which he says is impossible in c#? Isn't the worst outcome here someone wastes time trying to get a function to run something after it returns, and doesn't this worst case exist whether people might try to use it to overload ++ operator or otherwise? If there was no ++ someone could still try to do this with +=, and it would still be as impossible?

3

u/Mukhasim Mar 11 '20 edited Mar 11 '20

Here's my understanding of how to write the ++ operator in C#:

int operator ++ (int a) {
    return a + 1;
}

This defines both the prefix and postfix operator. When called, the language assigns a+1 to the variable, and it determines whether the expression has the value a or a+1 depending on whether you used it as a prefix or postfix operator.

It's actually very simple but not what you might think if you're coming from C++.

Disclaimer, I haven't tested or used this so I could be getting it wrong.

1

u/HolzmindenScherfede Mar 11 '20

even he has trouble keeping it straight in his head.

I am not surprised. I thought it would output 7 and 1 because I swapped ++x and x++

3

u/KuntaStillSingle Mar 11 '20

in C and C++ it's undefined behavior

Do compilers generally develop behavior for this or is it typically unsupported outright?

7

u/sepp2k Mar 11 '20

Code like in the OP will produce a warning in GCC and clang at least (if you enable warnings).

Besides that, the compiler will just lay out the code in whichever way it feels is best without worrying about how it affects behaviour that's not defined. So you might get different output on different compilers or even the same compiler with different optimizations enabled. For OP's code (translated to C of course) GCC will give you 9 and -1 as the output regardless of optimization level and clang will give 8 and 0 - also regardless of optimization level.

0

u/KuntaStillSingle Mar 11 '20

If anything that's a feature. 1/3 of your off by one errors could be fixed by using a different compiler )))))

1

u/MCPtz Mar 11 '20

Interesting... I put parens around (a++) and it's the same, evals to 8.

Simpler example of this operator's action:

	int a = 3;
	int t = a++;
	System.out.println(t);//Prints "3"
	System.out.println(a);//Prints "4"

If the user wanted to work around this with a temp variable:

    int a=3;
    a++;
    int t = a;
    ++a;
    t = t + a;
    System.out.println(t);//Will be "9"
    System.out.println(a);//Will be "5"

1

u/[deleted] Mar 12 '20

I'm confused. In the first example did you print the numbers in reverse by accident?

3

u/[deleted] Mar 11 '20

You should have a look at the Java bytecode for this class. It will shed some light on the order of what is happening. Pseudo bytecode below, just a guess though.

; ++a
inc a
push a
; a++
push a
inc a
; ++a + a++
add
; a =
store a

4

u/Mukhasim Mar 11 '20

Here's the output I get from javap.

$ javap -c Addit.class
Compiled from "Addit.java"
public class Addit {
  public Addit();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_3
       1: istore_1
       2: iconst_2
       3: istore_2
       4: iinc          1, 1
       7: iload_1
       8: iload_1
       9: iinc          1, 1
      12: iadd
      13: istore_1
      14: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      17: iload_1
      18: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
      21: iinc          1, -1
      24: iload_1
      25: iload_1
      26: iinc          1, -1
      29: isub
      30: istore_1
      31: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
      34: iload_1
      35: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
      38: return
}

5

u/[deleted] Mar 11 '20

Cheers, I've commented a snippet of it below.

   ; push 3 on the stack
   0: iconst_3  
   ; store 3 into variable 1 (a)
   1: istore_1
   ; ditto 2 -> b
   2: iconst_2
   3: istore_2
   ; increment variable 1 by 1
   4: iinc          1, 1
   ; load variable 1 onto the stack
   7: iload_1
   ; load variable 1 onto the stack
   8: iload_1
   ; increment variable 1 by 1
   9: iinc          1, 1
   ; pop the 2 values off the stack, add them, store the result
  12: iadd
   ; take the result off the stack and store it in variable 1 (a)
  13: istore_1
   ; invoke System.out.println
  14: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
  17: iload_1
  18: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V

2

u/Mukhasim Mar 11 '20

Thanks, I was hoping someone would do that!

2

u/proskillz Mar 12 '20

What do you do that you would need to know how to read java bytecode? Hmm. Maybe I need to up my game on low level java.

3

u/[deleted] Mar 12 '20

Program analysis, reverse engineering, security audits, hacking. Most (all?) of the Java decompilers are outdated, many of the RE tools have some subset of useful features but not all. A lot of times it is easier to just look at the bytecode.

I also have a fascination with Jazelle and hope to one day reverse engineer enough of it to present at a conference. The spec is not available. The short of it, is they took Java bytecode (usually interpreted by a program, the JVM) and made it work native on old ARM chips. Like fucking what?! Native Java bytecode???

Anyway, it is a stack based language. Pretty easy to understand and not a very complex instruction set. If you're interested in learning a stack based "low level" language, check out WASM though. It is much more modern and will probably be more profitable in the future. The search "wasm by hand" will bring up a few cool projects.

1

u/WikiTextBot Mar 12 '20

Jazelle

Jazelle DBX (direct bytecode execution) is an extension that allows some ARM processors to execute Java bytecode in hardware as a third execution state alongside the existing ARM and Thumb modes. Jazelle functionality was specified in the ARMv5TEJ architecture and the first processor with Jazelle technology was the ARM926EJ-S. Jazelle is denoted by a "J" appended to the CPU name, except for post-v5 cores where it is required (albeit only in trivial form) for architecture conformance.

Jazelle RCT (Runtime Compilation Target) is a different technology and is based on ThumbEE mode and supports ahead-of-time (AOT) and just-in-time (JIT) compilation with Java and other execution environments.

The most prominent use of Jazelle DBX is by manufacturers of mobile phones to increase the execution speed of Java ME games and applications.


Java bytecode instruction listings

This is a list of the instructions that make up the Java bytecode, an abstract machine language that is ultimately executed by the Java virtual machine. The Java bytecode is generated from languages running on the Java Platform, most notably the Java programming language.

Note that any referenced "value" refers to a 32-bit int as per the Java instruction set.


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28

1

u/proskillz Mar 12 '20

Thanks, I'll check it out.

2

u/[deleted] Mar 11 '20

Remember that ints are value types and not reference types.

So, the order of what happens here is this:

  1. a is assigned the value of 3.

  2. value-of-a is incremented (prefix unary operation occurs before the value is taken) to 4

  3. value-of-a (4) is added to value-of-a (4, remember that postfix unary operation happens after the value is read) to render 8

  4. the second value-of-a (4) is decremented to 3, but this is lost since the value has already been read

  5. a is assigned the value of 8.

(Step 4 above may actually be optimized out since it has no effect, and it may happen after step 5.)

The order is the same in the second assignment:

  1. value-of-a is decremented to 7

  2. value-of-a (7) is subtracted from value-of-a (7) to render 0.

  3. the second value-of-a (7) is decremented to 6, but this value is lost (see step 4 above)

  4. a is assigned the value of 0.

Finally: never, ever write code like this.

4

u/Otroletravaladna Mar 11 '20

Finally: never, ever write code like this.

Amen

4

u/sepp2k Mar 11 '20

Remember that ints are value types and not reference types.

The behavior doesn't change if you replace int with Integer (which is a reference type) in OP's code.

It also doesn't change if you create your own mutable reference type with methods like postInc(), preInc() etc.

3. value-of-a (4) is added to value-of-a (4, remember that postfix unary operation happens after the value is read) to render 8

4. the second value-of-a (4) is decremented to 3, but this is lost since the value has already been read

The side-effect of a++ is executed before the addition is evaluated, not after.

You can see the difference if we make a++ evaluate to 0 and replace the addition with a division (which throws an exception if the right operand is 0):

class Bla {
    public static void main(String[] args) {
        int a = -1;
        try {
            a = ++a / a++;
        } catch (Exception e) {
            e.printStackTrace();
        }        
        System.out.println(a);
    }
}

As you can see the value of a will be 1 afterwards, meaning the side-effect of a++ was executed before the division (otherwise the exception would have prevented it from executing and a would have been 0).

2

u/[deleted] Mar 11 '20

If this is the behavior of the postfix operator

a++ sets the value of a to 5 and evaluates to 4

then a++ should evaluate to 0 when used in the expression in your code.

I don't have a Java compiler handy, but I entered your class in four different online Java compilers and all of them threw "java.lang.ArithmeticException: / by zero".

I think you're confused about your example here, and you're making a distinction without a difference (i.e., saying the side effect is executed before evaluation and not after, when the end result is exactly the same in each of the cases presented).

3

u/sepp2k Mar 11 '20

then a++ should evaluate to 0 when used in the expression in your code.

Yes, a++ evaluates to 0 either way. What I'm saying is that the value of a afterwards will be 1.

If a were only incremented after the division, then a would still be 0 at the end because the division never finishes (it throws an exception).

Maybe this doesn't convince you because you think that the increment could just happen after the exception is being thrown (but before it's caught), so let's look at another type of expression instead: f(x++);. Would you say that x will be increased after f is called or before f is called? If you think it's increased after the call, the following code should serve as a counter-example:

class Bla {
    static int x = 0;

    static void f(int arg) {
        System.out.println("f was called with the argument " + arg + " and the value of x is " + x);
    }

    public static void main(String[] args) {
        f(x++);
    }
}

The result can be seen here. As you can see the value of x can already be observed to be 1 while f is running, so the increment must have happened before the method call, not after.

0

u/[deleted] Mar 11 '20

Maybe this doesn't convince you because

No, it didn't convince me because your previous example didn't work out the way you claimed it would. Particularly this part:

As you can see the value of a will be 1 afterwards, meaning the side-effect of a++ was executed before the division (otherwise the exception would have prevented it from executing and a would have been 0).

The "otherwise" part happened. Furthermore, your example code threw an error exactly as it would have had the a++ increment happened after the evaluation--which is what I was claiming originally.

Your second example is even more specious. at the moment the function is called, x is evaluated as 0, which, in the function body, is assigned to the variable arg. On the SECOND evaluation of x, it's value is 1, which indicates that the increment happened after between the first and second evaluations. And by "happened" I mean, "has any noticeable effect on the code".

3

u/sepp2k Mar 11 '20

The "otherwise" part happened.

No, it didn't. The code prints 1, not 0.

your example code threw an error

Which I said it would. The question was never whether the exception would be thrown. The question was whether a would be 1 or 0 after the exception. And it was 1.

On the SECOND evaluation of x, it's value is 1, which indicates that the increment happened after between the first and second evaluations

The fact that it happened at all was my point. The exception didn't prevent it from happening, so it must have happened before the exception, and thus before the division.

0

u/[deleted] Mar 11 '20 edited Mar 11 '20

Are you really so disingenuous to not understand that my quote was referring to your FIRST example (the one with the try/catch) and not the second one?

Forget it. If you're going to start arguing in bad faith, then this discussion ends.

EDIT: My bad. I overlooked the final print at the end. It does print 1. This doesn't change my understanding that postfix unary operation happens in evaluate-then-increment order (or decrement). What's the difference?

3

u/sepp2k Mar 11 '20

Are you really so disingenuous to not understand that my quote was referring to your FIRST example (the one with the try/catch) and not the second one?

What? No. You were referring to the first example and so was I. What makes you think I was referring to the second one (or that I thought/pretended to think that you were)? The second one doesn't even contain an exception.

1

u/[deleted] Mar 11 '20

I apologize. I didn't notice the "1" printed in the output after the first example, and was trying to make sense of everything you wrote in that mistaken context.

The exception didn't prevent it from happening, so it must have happened before the exception, and thus before the division.

So here's my quibble: when you say that the increment happens before the division, to me that entails that the *assignment* of the incremented value back to the variable ALSO happens before the division.

But apparently you're saying that

  1. the incremented value is stored (somewhere?)

  2. the variable is evaluated at its original value,

  3. the division happens with the variable's original value,

  4. and THEN the stored value is assigned to the variable.

It's just simpler for me to think evaluate-then-increment:

  1. the variable is evaluated at its original value, which is stored (somewhere?)

  2. the variable is incremented

  3. the stored value is used in the division

There's nothing in any of your examples (or any example I can think of) to distinguish between these two accounts.

2

u/sepp2k Mar 11 '20

It's just simpler for me to think evaluate-then-increment:

  1. the variable is evaluated at its original value, which is stored (somewhere?)

  2. the variable is incremented

  3. the stored value is used in the division

That's perfectly fine by me. But the way you wrote it in your first post, you had the increment after the addition. I.e. you had the addition in step 3 and the increment in step 4.

1

u/sepp2k Mar 11 '20

This doesn't change my understanding that postfix unary operation happens in evaluate-then-increment order (or decrement). What's the difference?

My objection wasn't that you said that the increment happens after the evaluation of x++ (that's not the way the standard defines it, but you're right that that's a distinction without a difference).

My objection was that you said the increment happens after the addition, i.e. after the evaluation of 4 + 4.

2

u/[deleted] Mar 11 '20

Fair enough. What I meant to indicate was that the value used in the addition was the pre-increment value. I now understand that the way I expressed it suggested consequences I did not intend.

0

u/MirrorLake Mar 11 '20 edited Mar 11 '20

For any some languages, questions like these are resolved by referring to the language's operator precedence. It's a much longer version of "PEMDAS" order of operations that you might have learned in algebra, but the same idea applies.

3

u/sepp2k Mar 11 '20

Not really. Precedence doesn't tell you whether the left operand is evaluated before the right. Neither does associativity - left-to-right associativity does not imply left-to-right evaluation (note that all operators are evaluated left-to-right in Java, even if the associativity is right-to-left).

Precedence also doesn't tell you in what order side-effects happen, nor does it explain the difference in semantic between ++x and x++.

So precedence and associativity aren't sufficient in explaining the behavior of OP's code (nor are they particularly helpful as the precedence of a = ++a + a++ is the one part that's pretty obvious).

Case in point: In C the involved operators have the same precedence and associativity as in Java, but the behavior is still different (undefined).

1

u/MirrorLake Mar 11 '20

My link has information about associativity as well, though. You can absolutely figure out the correct answer from it. I feel like I got thrown under the bus here.

3

u/sepp2k Mar 11 '20

My link has information about associativity

As I said, associativity is also irrelevant because it does not affect evaluation order. The article you linked also mentions that evaluation order always goes left-to-right, though. I admit I didn't fully read the article when I wrote my earlier reply - I just responded to your claim that "questions like these are resolved by referring to the language's operator precedence".

1

u/MirrorLake Mar 11 '20

It's not an article, it's a page from a Java textbook. It seems the main point of confusion for professionals and students alike is the post-decrement/increment operator does not do what people assume it does in Java. I was more or less trying to remind any students here that every textbook/language standard has a table devoted to helping you navigate these operator questions.

-3

u/SafeForWorkLife Mar 11 '20

So a problem like this is not solvable, unfortunately. General concepts and rules are broken by doing this. Different languages and compilers will interpret and execute this differently. Even different versions of the same compiler might handle this different.

Some people can trace to an answer, but without the answer probably would come up with the wrong one. The problem lies with order of operations across multiple assignments are not really defined anywhere. I am although not a Java expert, but I have come across this problem before.

8

u/sepp2k Mar 11 '20

The problem lies with order of operations across multiple assignments are not really defined anywhere.

The Java spec very much does define it, it's only undefined in other languages like C and C++. All Java compiler versions are guaranteed to produce the same result that OP got - otherwise they're not conforming.