Ranged for and references

As an example of what you can do with references, it is worth looking at the ranged for facility in C++11. The following code is quite straightforward; the array squares is initialized with the squares of 0 to 4:

    constexpr int size = 4;     int squares[size];      for (int i = 0; i < size; ++i)     {         squares[i] = i * i;     }

The compiler knows the size of the array so you can use ranged for to print out the values in the array. In the following, on each iteration, the local variable j is a copy of the item in the array. As a copy, it means that you can read the value, but any changes made to the variable will not be reflected to the array. So, the following code works as expected; it prints out the contents of the array: ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.