0

Here is my code. According to the print results, there is no difference, then what does the & symbol play here?

#include <stdio.h>
#include <iostream>
#include <Windows.h>

int main(void)
{
    std::cout << "Print test data\n" << std::endl;
    int a[5] = { 23,443,16,49,66 };

    for (auto &ii : a)
    {
        std::cout << "auto ii: " << ii << std::endl;
    }

    printf("\n");

    for (auto jj : a)
    {
        std::cout << "auto jj: " << jj << std::endl;
    }
    system("pause");

}
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
Jeaninez - MSFT
  • 3,210
  • 1
  • 5
  • 20

1 Answers1

5

Auto, for(auto x : range): This usage will create a copy of each element of the range.
Auto &, for(auto& x : range): when you want to modify the elements in range (without proxy class reference processing), use auto&.

ii is a reference, so in the loop body, if ii is modified, the corresponding element in a will also be modified.

jj is not a reference. In each loop, it is a copy of the corresponding element. Its modification will not affect the corresponding element in a. Since each loop creates a copy, it will bring system overhead.

If you want to ensure that the data in a is not modified and you want to improve the efficiency, you can use the form const auto & ii : a.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Suarez Zhou
  • 174
  • 7