Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the following list of behind the scenes inside the range-based for loop?

Tags:

c++

for-loop

I am studying C++ and I saw a range-based for loop like this:

for (int i : {1,2,3,4,5})     std::cout << i << ' '; 

What is the temporary {1,2,3,4,5} in the for loop behind the scenes?

like image 260
Hamza.S Avatar asked Jan 07 '19 08:01

Hamza.S


People also ask

What are range-based loops?

Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It 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.

How do you use a range-based loop?

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() .

Does range-based for loop use iterator?

Range-Based 'for' loops have been included in the language since C++11. It automatically iterates (loops) over the iterable (container). This is very efficient when used with the standard library container (as will be used in this article) as there will be no wrong access to memory outside the scope of the iterable.

Are range-based for loops faster?

Range-for is as fast as possible since it caches the end iterator[citationprovided], uses pre-increment and only dereferences the iterator once. Then, yes, range-for may be slightly faster, since it's also easier to write there's no reason not to use it (when appropriate).


2 Answers

The object here is an instance of std::initializer_list<int>. From the reference (emphasis mine):

A std::initializer_list object is automatically constructed when:

a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an std::initializer_list parameter

a braced-init-list is used as the right operand of assignment or as a function call argument, and the corresponding assignment operator/function accepts an std::initializer_list parameter

a braced-init-list is bound to auto, including in a ranged for loop

like image 154
taskinoor Avatar answered Oct 02 '22 15:10

taskinoor


What is the temporary {1,2,3,4,5} in the for loop behind the scenes?

a std::initializer_list<int>

like image 43
Jarod42 Avatar answered Oct 02 '22 16:10

Jarod42