Search code examples
c++c++11initializer-list

The type of a bracketed sequence


Let's consider the following code:

for(std::size_t j : {0,1,2,3,4,5,6,7})
{
   // do something with j
}

What will be the underlying type created by the compiler for the sequence {0,1,2,3,4,5,6,7}?

Will it be a std::vector<T> and std::array<T, 8> or an std::initializer_list<T>? (where T is either int or std::size_t).


I don't consider this to be a duplicate of Ranged for loop with literal list? since I specifically would like to know about the situation whether the type (std::size_t in this case) of the variable used to iterate over the std::initializer_list<int> will influence the compiler or not.


Solution

  • I specifically would like to know about the situation whether the type std::size_t of the varibale used to iterate over the std::initializer_list will influence the compiler or not

    It won't. The equivalent statement as specified by the standard, and in the question you linked to, ends up with something like this:

    auto && __range = {0,1,2,3,4,5,6,7};
    //...
    for(/*...*/) {
       std::size j = *__begin;
       // ...
    }
    

    There is no explicit requirement for j to influence the deduction of __range, and nor should it according to the general rules of scope. j will just be initialized with a converted int.