c++ranged-loops

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?


Solution

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