Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the range-based for work for plain arrays?

In C++11 you can use a range-based for, which acts as the foreach of other languages. It works even with plain C arrays:

int numbers[] = { 1, 2, 3, 4, 5 }; for (int& n : numbers) {     n *= 2; } 

How does it know when to stop? Does it only work with static arrays that have been declared in the same scope the for is used in? How would you use this for with dynamic arrays?

like image 618
Paul Manta Avatar asked Oct 29 '11 14:10

Paul Manta


People also ask

Can we use range based for loop for array in C++?

Range-based for loop in C++ Also Sequence of elements in braces can be used. loop-statement − body of for loop that contains one or more statements that are to be executed repeatedly till the end of range-expression.

Why you Cannot use a range based for loop on dynamic arrays?

You can't perform a range based loop directly over a dynamically allocated array because all you have is a pointer to the first element. There is no information concerning its size that the compiler can use to perform the loop.


1 Answers

It works for any expression whose type is an array. For example:

int (*arraypointer)[4] = new int[1][4]{{1, 2, 3, 4}}; for(int &n : *arraypointer)   n *= 2; delete [] arraypointer; 

For a more detailed explanation, if the type of the expression passed to the right of : is an array type, then the loop iterates from ptr to ptr + size (ptr pointing to the first element of the array, size being the element count of the array).

This is in contrast to user defined types, which work by looking up begin and end as members if you pass a class object or (if there is no members called that way) non-member functions. Those functions will yield the begin and end iterators (pointing to directly after the last element and the begin of the sequence respectively).

This question clears up why that difference exists.

like image 143
Johannes Schaub - litb Avatar answered Sep 22 '22 15:09

Johannes Schaub - litb