Search code examples
c++referenceautorange-based-loop

What is different between two codes of for loop?


#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto &x : a)
        cout << x << endl;
}
#include <vector>
#include <iostream>
using namespace std;

int main(void)
{
    vector<int> a = {1, 2, 3, 4, 5};
    for (auto x : a)
        cout << x << endl;
}

Two codes above prints same values (1, 2, 3, 4, 5). But is there different thing between initializing &x and x? Thanks for reading!


Solution

  • There is no difference in the output for the code you wrote. However, if you tried to change the value of x when in the loop, there would be a difference.

    #include <vector>
    #include <iostream>
    using namespace std;
    
    int main(void)
    {
        vector<int> a = {1, 2, 3, 4, 5};
        for (auto x : a)
            x = 0;
        for (auto x : a)
            cout << x << endl;
    }
    

    is very different to:

    #include <vector>
    #include <iostream>
    using namespace std;
    
    int main(void)
    {
        vector<int> a = {1, 2, 3, 4, 5};
        for (auto & x : a)
            x = 0;
    
        for (auto x : a)
            cout << x << endl;
    }
    

    In the second, the vector a will be all zeros at the end of the program. This is because auto by itself copies each element to a temporary value inside the loop, whereas auto & takes a reference to an element of the vector, which means that if you assign something to the reference it overwrites wherever the reference is pointing.