Declaring variable as i vs &i in the foreach loop

  ampersand, c++, for-loop, foreach, loops

Why do these loops give the same output:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector<int> ar = {2, 3 ,4};
    for(auto i: ar) //this line changes in the next loop
        cout<<i<<" ";

    cout<<"n";

    for(auto &i: ar) //i changed to &i
        cout<<i<<" ";
}

They both give the same output:

2 3 4

2 3 4

When declaring the foreach loop variable, shouldn’t adding ampersand make the variable take the references of the values in the array, and printing i make it print the references. What is happening here?

By print the references I meant something like this code prints:

for(auto i: ar)
    cout<<&i<<" ";

Output:

0x61fdbc 0x61fdbc 0x61fdb

Source: Windows Questions C++

LEAVE A COMMENT