Help with a test qn

Apr 16, 2019 at 11:37am
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;
}
Apr 16, 2019 at 11:47am
The life cycle of I is only in the loop, and the I in the second loop is redefined.
Apr 16, 2019 at 11:55am
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.