By Hamza.S


2019-01-07 08:21:29 8 Comments

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?

2 comments

@Jarod42 2019-01-07 08:23:47

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

a std::initializer_list<int>

@CodeIt 2019-01-08 02:14:10

Could have added some text from that link.

@taskinoor 2019-01-07 08:25:02

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

@Rakete1111 2019-01-08 08:51:14

The braced initializer list is not an object, but I guess pretending that it is is fine in this case.

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] C++11 reverse range-based for-loop

  • 2011-12-17 04:29:25
  • Alex B
  • 85499 View
  • 276 Score
  • 7 Answer
  • Tags:   c++ c++11

11 Answered Questions

5 Answered Questions

[SOLVED] How to use range-based for() loop with std::map?

23 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

7 Answered Questions

[SOLVED] How to make my custom type to work with "range-based for loops"?

17 Answered Questions

[SOLVED] Why should C++ programmers minimize use of 'new'?

3 Answered Questions

[SOLVED] Double to int conversion behind the scene?

2 Answered Questions

[SOLVED] How to use ranged-based for loops with std::weak_ptr

  • 2014-04-02 19:11:33
  • Marc A.
  • 142 View
  • 1 Score
  • 2 Answer
  • Tags:   c++11 for-loop

3 Answered Questions

[SOLVED] How is the range-based loop different to a for-each loop?

  • 2012-04-17 11:07:38
  • charisis
  • 3985 View
  • 5 Score
  • 3 Answer
  • Tags:   c++ for-loop c++11

Sponsored Content