1

EDIT: This is for my Java class. In class, my prof did a similar problem and the answer he's expecting will most definitely be a number.
EDIT: (left to right), (right to left) is the associativity of operator

int a = 3;
int b = a++ + ++a + a * 2 + ++a;
//So b = 24 & a = 6 

I am uncertain to why this is the answer. My reasoning is:

int a = 3;
int b = a++ + ++a + a * 2 + ++a;
        (3) + (5) + (5 * 2) + (6)
        //a is 3, increments to 4 but stays as 3 [a++]
        //a is now 4 but increments to 5 [++a]
        //Since I'm evaluating left to right [a * 2] is [5 * 2]. This is because a holds the value 5.
        //a is 6 [++a]

Is my logic correct? Does the compiler evaluate it like this? I understand that the order of precedence in terms of this question, where var is an arbitrary variable, goes like:

"post" --------------> var++ & var-- (left to right)

"pre" ---------------> ++var & --var (right to left)

"multiplication" ----> * var & var* (left to right)

What is the general rule for stuff like this if instead we were taking the power, dividing, or modulating a variable in an expression like this?

Charlie
  • 11
  • 3
  • No idea what is (left to right) still your logic about the quoted code is correct. If it was C then the result will be undefined but in `Java 8` it will be 24( 3 + 5 + 2 * 5 + 6). – dbl Oct 18 '18 at 06:13
  • @MadPhysicist When I print out a & b after the evaluation b prints 24 and a prints 6 – Charlie Oct 18 '18 at 06:32
  • 1
    @Someprogrammerdude: No, it's not undefined. The JLS *does* specify an order. – Jon Skeet Oct 18 '18 at 06:52

0 Answers0