-2

Why doesn't the range-based loop with auto display addresses? The for loop:

for (int i = 0; i < s; i++) cout << &ar[i] << endl; 

works normally, but range-based loop with auto doesn't:

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int ar[] = { 12,-23,0,1,2 };
    int s = sizeof(ar) / sizeof(int);
    int * m = &ar[0];
    sort(&ar[0], m+ s);
    for (auto m : ar)
        cout << m << endl;
    cout << endl;
    for (auto m : ar)
        cout << &m << endl;
    cout << endl;
    for (int i = 0; i < s; i++)
        cout << &ar[i] << endl;
    system("pause");
}
Ron
  • 14,674
  • 4
  • 34
  • 47

1 Answers1

7

With the auto m you are passing (array) elements by value / copy in your range based loop:

for (auto m : ar) { // pass by value
    std::cout << &m << ' '; // prints addresses of copies, not the actual array elements
}

This means m becomes a copy of an array element in each iteration and has its own address in the memory.

If you passed by reference (auto& m) or a reference to const (const auto& m), you would observe the expected results:

for (auto& m : ar) { // pass by reference
    std::cout << &m << ' '; // prints addresses of the actual array elements
}

Now m is an actual array element and &m represents the array element address as expected.

Ron
  • 14,674
  • 4
  • 34
  • 47