godMode
godMode

Reputation: 381

Return Array index and increment at the same time

How does Java, Kotlin, and Android handle returning an Array value at a given index while incrementing the index value?

int[] someArray = new int[5];
int index = 0;
int result;

result = someArray[index++];

Which index would be passed to the result? Will it increment index first, then pass it to someArray[1], or will it pass the original value of index to someArray[0] and then increment index?

Upvotes: 19

Views: 30979

Answers (5)

andronikus
andronikus

Reputation: 4210

See: Java documentation, Assignment, Arithmetic, and Unary Operators:

The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.

So you'll get someArray[0].

Upvotes: 20

Brandon Langley
Brandon Langley

Reputation: 551

1.) Avoid doing this sort of thing, in fact with code I review I ask people to never do this.

Not specifically using ++, but the fact you're doing it as part of evaluating something else. Generally it won't cost the compiler any extra to have that increment as a separate statement, and putting it inline like that means the next person coming along has to take a second and evaluate the increment themselves.

I know it's minor, and it's a little nitpicky, but stuff like this costs extra time during code review, it's easy to miss while scanning, etc. And it saves you nothing but a few extra keystrokes, which when compared against code clairity and readability is not worth it IMO.

2) You will get someArray[0], and after moving on to the next line, you will have your index incremented.

Upvotes: 1

Gravity
Gravity

Reputation: 2744

index++ returns index and then increments by 1. So it will do result = someArray[0] and then set index to 1.

In contrast, ++index would do the increment and then pass the incremented value. So if you wanted result set to someArray[1] in the above code, you would use ++index.

As someone else said, please don't use this kind of syntax. Instead, please write

index++;
result = someArray[index];

Upvotes: 6

derekerdmann
derekerdmann

Reputation: 18252

In Java and similar languages, using index++ only increment the value after the expression has been evaluated. If you want to increment before using the variable, use ++index.

In this case, it will use the original value of index to obtain result, and then increase its value to 1.

Upvotes: 4

Soufiane Hassou
Soufiane Hassou

Reputation: 17750

It will pass someArray[0] and then increment index

It is not dependent from android, the general rule is:

index++ means evaluates index and then increment it, while ++index is increment then evaluate

Upvotes: 3

Related Questions