int arr[] = {0,1,2,3,4,5};
for (int i : arr){
i = 1;
}
(Question 1): Why does this code segment not produce an error since it is using a for-each loop to modify elements?
int arr[] = {0,1,2,3,4,5};
for (int i : arr){
arr[i] = 1;
}
(Question 2): How does this code work even though the for each-loop is not being used properly. Nonetheless, somehow all the elements are set to 1?
Thank you for your help.
(Question 1): Why does this code segment not produce an error since it is using a for-each loop to modify elements?
It doesn't modify elements. What it does is modify the variable i, which at any point in time happens to contain a copy of one of the elements, but is otherwise completely unrelated to the array.
(Question 2): How does this code work even though the for each-loop is not being used properly.
The loop may indeed look peculiar, but there's nothing fundamentally wrong with it. It is equivalent to the following code:
arr[0] = 1;
arr[1] = 1;
arr[2] = 1;
arr[3] = 1;
arr[4] = 1;
arr[5] = 1;
Of course this only works because arr happens to contain valid indices into itself. If it didn't (for example, if arr[0]=6), you'd get an ArrayIndexOutOfBoundsException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With