Home > Article > Backend Development > How do C 11 Range-Based Loops Work Under the Hood?
Behind the Scenes of C 11 Range-Based Loops
Range-based loops offer a concise syntax for iterating over elements of a collection, but their inner workings may not be immediately apparent.
Variable Initialization
While it may seem that the loop variable (in this case, x) is initialized only once, the reality is different. In a range-based loop like:
<code class="cpp">for (const int x : vec) { cout << x << endl; }</code>
The compiler creates a new local variable x for each iteration. It initializes x to the value of the next element in the vec vector.
Const Variables
Despite being declared const, the x variable can appear to change in each iteration because it's not the same variable. Each newly created x is assigned to the next element of vec, giving the illusion that the same variable is being modified.
Implementation Details
Range-based loops are implemented using iterators, which are objects that provide access to the elements of a collection. In the above code, vec has an iterator returned by begin() and end() functions. The iterator is used to step through the elements, and x is assigned to the value pointed to by the iterator.
Additional Notes
The above is the detailed content of How do C 11 Range-Based Loops Work Under the Hood?. For more information, please follow other related articles on the PHP Chinese website!