Rikard Rasmussen
Rikard Rasmussen

Reputation: 15

Confused about ranged for loops

To me, this doesn't produce the expected results:

int main() {

    int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

    for (auto v : i)
        std::cout << v << std::endl;

    for (auto v : i)
        v = v+1;

    for (auto v : i)
        std::cout << v << std::endl;

    return 0;
}

The second for loop doesn't seem to do anything. Are range-based for loops read-only, or am I missing something?

Upvotes: 1

Views: 57

Answers (1)

Yang
Yang

Reputation: 8170

In your second loop, auto v : i, v is a copy of each i.

To change the i values, you need a reference:

int main() {
  int i[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };

  for (auto v : i)
    std::cout << v << std::endl;

  for (auto& v : i)  // Add "&" here. Now each v is a reference of i.
    v = v + 1;

  for (auto v : i)
    std::cout << v << std::endl;

  return 0;
}

Demo: https://ideone.com/DVQllH.

Upvotes: 3

Related Questions