Neon
Neon

Reputation: 41

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

Upvotes: 0

Views: 517

Answers (2)

Lyuboslav Alexandrov
Lyuboslav Alexandrov

Reputation: 367

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.

Upvotes: 2

Hi - I love SO
Hi - I love SO

Reputation: 635

The ampersand operator has many purposes. These two of the many are hard to recognize, namely the & infront of a variable in a declaration ( such as int& i ( or int &i, same thing ) ), and the & infront of a variable not in a declaration, such as cout << &i.

Try these and you will get a better understanding.

for (auto i : ar)
    cout << i << " "; // 2 3 4 // element of ar
    
for (auto &i : ar)
    cout << i << " "; // 2 3 4 // element of ar

for (auto i : ar)
    cout << &i << " "; // address of local variable i (probably same address)
    
for (auto &i: ar)
    cout << &i << " "; // address of elements of ar (increasing addresses)

Upvotes: 2

Related Questions