Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reference to pointer as a sequence in C++11 range for loop

Tags:

c++

c++11

The only difference between the following two snippets of code is the usage of reference. I understand why the first snippet does not compile and am seeking help in understanding why the second one compiles.

The first snippet:

int a[2][3] = {0,1,2,3,4,5};
for (auto row : a)
  for (auto column : row)
    cout << column << endl;

The above code does not compile because the type of 'row' is pointer to int, which is not a sequence.

The second snippet:

int a[2][3] = {0,1,2,3,4,5};
for (auto &row : a)
  for (auto column : row)
    cout << column << endl;

This code compiles. If I understand correctly how auto works, 'row' is a reference to pointer to int. But why can this reference be viewed as a sequence more than a regular pointer?

like image 482
AlwaysLearning Avatar asked Dec 15 '14 10:12

AlwaysLearning


People also ask

Are there range-based for loops in C?

Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.

What is ranged loop?

C++11 introduced the ranged for loop. This for loop is specifically used with collections such as arrays and vectors. For example, // initialize an int array int num[3] = {1, 2, 3}; // use of ranged for loop for (int var : num) { // code } Here, the ranged for loop iterates the array num from beginning to end.

How do you use the Range function in CPP?

Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .


1 Answers

Deduction of the type is done via template argument deduction.

template <typename U>
void foo(U&); // Equivalent to auto&

foo(row);

This will always deduce U to be the exact type of row (if it's an lvalue as in this case), which gives us the array type we desired.
Only for non-reference parameters is the array-to-pointer decay performed.

like image 156
Columbo Avatar answered Oct 03 '22 07:10

Columbo