-3

this is my first question here, and I'm glad to join the community. I have a test tomorrow, and in one of the examples there is that line

i=0; j=2; z=2
i=j--;

What is the exact operation that is done? Because I know that j-- means j-1 everytime. Thanks! I'm using Dr.Java.

EDIT: It was a duplicate. Should I delete?

Román
  • 136
  • 1
  • 9

4 Answers4

6

i = j--; is an assignment statement. The right-hand side is evaluated, and the resulting value is assigned to the thing on the left-hand side. In your case, that means:

  1. The value of j is read (2, in that code)
  2. j is decremented (to 1, in that code)
  3. The value read in step 1 (2) is assigned to i

The order of Steps 1 and 2 is because the -- is after the j; it's the postfix decrement operator. If it were before the j (the prefix decrement operator), steps 1 and 2 would be reversed.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Okay, thanks. And one supplementary question: with i = 3; j = 2; z= 2, we have z= i++%j; what should i do on that line? – Román Nov 06 '16 at 13:21
  • @Román: If you break it down into its parts (as above), what do *you* think happens? – T.J. Crowder Nov 06 '16 at 13:25
  • I'm not sure, but think it's the same as you said before: First we assign to z the value of i%j (in this case 3%2, so z=1) and then we do in a next line i++ so i+1 (in this case 3+1). Am I right? I'm really thankfull for your help, my first months of programming and loving it! – Román Nov 06 '16 at 13:55
4

It means set i equal to j and then subtract one from j.

Jeremy Kahan
  • 3,796
  • 1
  • 10
  • 23
1

It is another shortcut for this code.

i=0; j=2; z=2
i = j;
j = j - 1;
Enzokie
  • 7,365
  • 6
  • 33
  • 39
0

This means that i will have as value 2, because you used a post-decrement operator. J will have the value of 1 since it is decremented. If you had written:

i = --j

then i will have the value of 1, since the value is decremented BEFORE assignment.

Gerald

Gerald Shyti
  • 51
  • 1
  • 6