0

Am I thinking right? How to rewrite below to simple assigments to show how the operations are done?

int a = 3;
int b;

b = --a * --a;

Java does:

b = (a=a-1) * (a=a-1) = (2) * (1) = 1;

int a = 3;
int b;

b = a-- * a--;

Java does:

b = a; a=a-1;b=b*a;a=a-1;

b=3;a=3-1=2;b=3*2=6;a=2-1=1;

michealAtmi
  • 1,012
  • 2
  • 14
  • 36
  • You should read on [Java's operator precedence](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html). – Laf Mar 03 '16 at 19:24
  • Yeah I read something similar and I can calculate the results and they are correct but I just want to rewrite these operations to simple assignments keeping order of operations just for learning purposes. – michealAtmi Mar 03 '16 at 19:26
  • 2
    what you have is right except that 2 * 1 isn't 1. :-) – Nathan Hughes Mar 03 '16 at 19:29
  • 1
    @michaelAtmi Your simplified code is correct. Problem solved? – Nayuki Mar 03 '16 at 19:31
  • b=3;a=3-1=2;b=3*2=6;a=2-1=1; should be a=3;a=3-1=2;b=3*2=6;a=2-1=1; right ?? – Kumar Mar 03 '16 at 19:34
  • Possible duplicate of [Incrementor logic](http://stackoverflow.com/questions/33120663/incrementor-logic) – Yassin Hajaj Mar 03 '16 at 20:06

2 Answers2

1

ok so in java the a--, first evaluates the a then it applies the operation (in this case subtraction),

for example:

   a=3;
   b=a--;

'b' will take the initial value of 'a' (b=3) and 'a' will then decrement (a=2).

In the following example:

    int a=3;
    int b;
    b= a-- * a--;
    System.out.println("a = " + a);
    System.out.println("b = " + b);

1. b=current value of a (3)
2. a=a-1 (2)
3. b=b * current value of a (b = 3 * 2)
4. a=a-1 (1)

And our result will be:

    b=6 a=1

for --a, java first applies the operation then it takes the value;

for example:

   a=3;
   b=--a;

'a' will decrement (a=2) and then 'b' will take the value of 'a' (b=2).

Example:

    int a=3;
    int b;
    b= --a * --a;
    System.out.println("a = " + a);
    System.out.println("b = " + b);

1. a=a-1 (2)
2. b=value of a (2)
3. a=a-1 (1)
3. b=b * value of a (b = 2 * 1)
And our result will be:

    b=2 a=1

hope this helps. good luck have fun :)

0
    int a = 3;
    int b = --a * --a;
    System.out.println("pre " + b + "/" + a);

    a = 3;
    int r1 = a-1;   // 2
    a = r1;         // 2
    int r2 = a-1;   // 1
    a = r2;         // 1
    b = r1 * r2;    // 2
    System.out.println("pre2 " + b + "/" + a);


    a = 3;
    b = a-- * a--;
    System.out.println("post" + b + "/" + a);

    a = 3;
    r1 = a;         // 3
    a = r1 - 1;     // 2
    r2 = a;         // 2
    a = r2 - 1;     // 1
    b = r1 * r2;    // 6
    System.out.println("post2 " + b + "/" + a);

Where r1 and r2 are pushed / popped from the stack for multiplication.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138