Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
godMode Avatar asked Aug 28 '11 00:08

godMode


People also ask

How do you increment an index of an array?

To increment a value in an array, you can use the addition assignment (+=) operator, e.g. arr[0] += 1 . The operator adds the value of the right operand to the array element at the specific index and assigns the result to the element.

Can you increment an array?

No, it's not OK to increment an array. Although arrays are freely convertible to pointers, they are not pointers. Therefore, writing a++ will trigger an error.

How do you increment an array in C++?

You increment it the same way as you would any other variable. You use the ++ operator with the array element you want to increment.


1 Answers

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].

like image 65
andronikus Avatar answered Nov 16 '22 01:11

andronikus