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

C++For Loop

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

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

a std::initializer_list<int>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHamza.SView Question on Stackoverflow
Solution 1 - C++taskinoorView Answer on Stackoverflow
Solution 2 - C++Jarod42View Answer on Stackoverflow