0

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
  • 3
    `std::initializer_list`. Looking at the definition of [range-for](http://en.cppreference.com/w/cpp/language/range-for), the range part is computed first, without regard to the type of the enumerating variable. So it works off the type of initializers, which in your case are all numeric literals of type `int`. – Igor Tandetnik Oct 30 '17 at 12:23
  • 1
    https://stackoverflow.com/questions/21689388/ranged-for-loop-with-literal-list – msc Oct 30 '17 at 12:26

1 Answers1

4

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • 1
    the last snippet is invalid: "error: deduced conflicting types ('unsigned long' vs 'int') for initializer list element type" https://godbolt.org/g/5vuc39 – bolov Oct 30 '17 at 17:36
  • @bolov - Incredible. [It works for a `std::pair`](https://stackoverflow.com/questions/46281477/range-based-for-over-pair-list/46281634#46281634), but not a `std::size_t`. C++ never ceases to amaze me. – StoryTeller - Unslander Monica Oct 30 '17 at 17:43
  • it works for `std::size_t` also :p https://godbolt.org/g/pDMWsk You just have to make the type of the other elements deductible. i.e. make them `{elem}` I am sure that is not the right terminology, but you get the point – bolov Oct 30 '17 at 17:46
  • @bolov - That should be my cue that I've had too much SO for one day :P – StoryTeller - Unslander Monica Oct 30 '17 at 17:47
  • 1
    C++ quota reached. Going to sleep mode :) – bolov Oct 30 '17 at 17:48