0

I understand that if I have the following assignment

arr[i++] = 1 is equivalent to

arr[i] = 1; 
i++;

But does

arr1[i++] = arr2[j++]

is equivalent to

arr1[i] = arr2[j];
i++;
j++;

What about

int i = 0;
while(i++ < 5){ 
    // do something...
}

Does the machine execute the //do something first then increase 1 and then evaluate whether i is currently < 5?

Can someone please help me to understand this?

Nadim Baraky
  • 459
  • 5
  • 18
Guifan Li
  • 1,543
  • 5
  • 14
  • 28
  • 5
    Yes, they are equivalent. Not sure what you're asking. – nhouser9 Oct 28 '16 at 18:03
  • 1
    You could just test it and see by yourself. But anyway, your interrogation is a clear sign that such code is hard to understand, and should thus be avoided at all cost. Putting as many instructions as possible in a single line of code only makes the code harder to read and maintain. – JB Nizet Oct 28 '16 at 18:05
  • `i++` increments immediately, and returns the previous value. – 4castle Oct 28 '16 at 18:11
  • `Can someone please help me to understand [Java basics]?` [sunsoft/oracle/whoever tried](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html). – greybeard Oct 28 '16 at 18:11
  • See also http://stackoverflow.com/questions/6800590/what-are-the-rules-for-evaluation-order-in-java – Tunaki Oct 28 '16 at 18:18

1 Answers1

5

Actually, arr[i++] = 1 is equivalent to

int i1 = i;
i = i + 1;
arr[i1] = 1;

The difference becomes relevant in an expression like

arr[i++] = i;

where i has been incremented by the time its value is written to the array. I hope this is enough information to resolve your question.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • The best place to remember is this: https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.7 It gives you one simple rule of thumb: expression are _always_, with no exceptions, evaluated from left to right. – Marko Topolnik Oct 28 '16 at 19:41