Help with a test qn

Why is the output 1,2,3,4,5 even after adding 10 to each of them? Revising for a test.
1
2
3
4
5
6
7
8
9
#include <iostream>
int main(void) {
    int a[] = { 1, 2, 3, 4, 5 };
    for (int i : a)
         i += 10;
    for (int i : a)
         std::cout << i << ' ';
    return 0;
}
The life cycle of I is only in the loop, and the I in the second loop is redefined.
If you want to modify the content of the array you need a reference. Currently you modify a copy.

1
2
3
4
5
6
7
8
9
#include <iostream>
int main(void) {
    int a[] = { 1, 2, 3, 4, 5 };
    for (int &i : a) // Note: &
         i += 10;
    for (int i : a)
         std::cout << i << ' ';
    return 0;
}
Topic archived. No new replies allowed.