2
for (int& i : array) {
    //do something on i
}

Does this count as "reseating reference i to different objects"?

This, appearently, let i refers to array[0] in first iteration, array[1] in second iteration, ..., and so forth.

Edit 1 in response to comment: I know exact what happens in implementation level. I used compiler explorer to see what does this compile to and I know that this looks completely same as other type of iteration (some level of optimization is assumed). This question is more about on the language level, not implementation.

Zackham
  • 45
  • 5
  • No, it's just like declaring a shortcut variable inside a regular for loop. [How is the range-based loop different to a for-each loop?](https://stackoverflow.com/questions/10190045/how-is-the-range-based-loop-different-to-a-for-each-loop) – Retired Ninja Jan 30 '23 at 01:13
  • 2
    I've never heard of the term "reseating", but what this does do is create a *new* reference in each iteration of the loop, referring to each successive element of the array – Chris Dodd Jan 30 '23 at 01:19
  • @ChrisDodd There is no such thing as "create a new reference", see in my Edit 1. It is still a counter/address offset based loop. – Zackham Jan 30 '23 at 01:26
  • According to the equivalence code here, it does appear to create a new reference each iteration round the loop: https://en.cppreference.com/w/cpp/language/range-for – Galik Jan 30 '23 at 01:30
  • 3
    Creating a new reference in each iteration would look like this in a regular for loop. `for (int n = 0; n < limit; ++n) { int& i = array[n]; ... }` In each iteration `i` is a new reference. How the compiler generates code for that is an implementation detail, but from a language standpoint there is no reseating happening.. – Retired Ninja Jan 30 '23 at 01:30
  • @RetiredNinja Well then that is indeed a self logically consistent explanation, I'll just accept that anyway... – Zackham Jan 30 '23 at 01:45

0 Answers0