Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 range based loop: How does it really work

Tags:

c++

c++11

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?

like image 705
AC Voltage Avatar asked Nov 05 '15 22:11

AC Voltage


People also ask

What is range-based for loop in C++?

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.

What is the difference between c++17 and C++20 for loop?

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.

Which STL data structures can be iterated over with range-based for loops?

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?

Is C++11 a good language to learn?

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.


1 Answers

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.

like image 112
Brian Bi Avatar answered Oct 25 '22 20:10

Brian Bi