- [Narrator] Beginning with the 2011 version of C++
there's a new range based for a loop.
This gives C++ a simple way
of iterating over the elements of a container
and operation that used to take a bit more code.
This is range-for.cpp
from chapter two of the exercise files.
And you'll see that we have a symbol array
with five elements,
and this very different looking for-loop.
The first part of the control
on the for-loop declares a variable,
and then there's a colon, and then there is a container.
So what happens is for each element of the container,
the variable is set to the value of that element,
and it's passed into the block where you can use it.
And so when I build and run this,
you see that I'm simply displaying
each of the elements from the array.
It's very simple and it's quite different from the C4 loop,
but you can see where it could be quite useful.
It's mostly used in iterating over
the elements of a container.
And when we get into the STL
which is basically a library of containers,
you'll see how this is very useful
in C++ more so than it would be in C
which doesn't have anything like the STL.
So, let's take a look at this with a string
because what's interesting about this
is that you'll notice it's not looking
for the end of the array,
it's not checking against a constant that says,
"well, this array has five elements"
because it knows at compile time
what is the size of this array.
But it doesn't know the size of a string
because a string is null terminated.
And so if I declare a string,
and we're going to use a character and we'll call a C,
and we'll say "C is" like that.
Now if I go ahead and run this,
it'll go through the entire array
which has seven elements including the null terminator.
If I want to end this at the null terminator
I need to put in a condition here,
I need to say "if(C = 0)," and then break.
And now it'll work like a for-loop with a string.
And you can see we have our six elements of the string.
So it's not as convenient for strings,
with strings you more often see
the other type of for-loop
because it has controls for checking
for the end of the string much more easily.
But for many containers you'll find
that this is a very, very convenient way
to iterate through.
This is the range based for-loop,
it's very powerful and useful in C++ 11 and later.
Earlier versions of C++ do not have this.
It provides a simple and effective solution
for iterating over the elements of a container.
It works just as well with native arrays,
vectors strings, initialize arrays
and anything that supports sequential iterators.
And we'll talk more about iterators
in the separate C++ templates in the STL course.
So we'll talk about them
a little bit in the STL chapter here
but more in the later course.
As new code is written in C++ and older code is updated,
the range based for-loop is becoming very common.