I know how this loop works, and how I can use it in practical problems. But I want to know what is happening under the hood.
I thought that this loop was similar to a regular for
loop in which for example
for(int i = 0 ; i < 5 ; i ++){
// instructions
}
Variable i
is initialized only once, so I thought that this was the same for range based loops. But if I for example write this code:
for(const int x : vec) {
cout << x << endl;
}
The compiler lets me to do this, but I don't understand how this is possible. If variable x
is const
, how come in every iteration the x
value is different?
Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
The range-based for loop changed in C++17 to allow the begin and end expressions to be of different types. And in C++20, an init-statement is introduced for initializing the variables in the loop-scope.
Strings, arrays, and all STL containers can be iterated over with the new range-based for loop already. But what if you want to allow your own data structures to use the new syntax?
In the first article introducing C++11 I mentioned that C++11 will bring some nice usability improvements to the language. What I mean is that it removes unnecessary typing and other barriers to getting code written quickly.
Every iteration of the loop creates a local variable x
and initializes it to the next element of vec
. When the loop iteration ends, x
goes out of scope. A single x
is never modified.
See this link for the precise semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With