Search code examples
c++loopsfor-loopforeachampersand

Declaring variable as i vs &i in the foreach loop


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


Solution

  • The results are the same because in the first loop you copy the variable's value in a new variable i and print its value. (Additional RAM allocated)

    In the second loop you access the value of the current element from the memory by assigning its address to i. (No additional RAM allocated)

    On the other side:

    cout<<&i<<" ";
    

    causes printing the address of i.