6.12a — For-each loops

In lesson 6.3 -- Arrays and loops, we showed examples where we used a for loop to iterate through each element of an array.

For example:

While for loops provide a convenient and flexible way to iterate through an array, they are also easy to mess up and prone to off-by-one errors.

C++11 introduces a new type of loop called a for-each loop (also called a range-based for loop) that provides a simpler and safer method for cases where we want to iterate through every element in an array (or other list-type structure).

For-each loops

The for-each statement has a syntax that looks like this:

for (element_declaration : array)

When this statement is encountered, the loop will iterate through each element in array, assigning the value of the current array element to the variable declared in element_declaration. For best results, element_declaration should have the same type as the array elements, otherwise type conversion will occur.

Let’s take a look at a simple example that uses a for-each loop to print all of the elements in an array named fibonacci:

This prints:

0 1 1 2 3 5 8 13 21 34 55 89

Let’s take a closer look at how this works. First, the for loop executes, and variable number is set to the value of the first element, which has value 0. The program executes the statement, which prints 0. Then the for loop executes again, and number is set to the value of the second element, which has value 1. The statement executes again, which prints 1. The for loop continues to iterate through each of the numbers in turn, executing the statement for each one, until there are no elements left in the array to iterate over. At that point, the loop terminates, and the program continues execution (returning 0 to the operating system).

Note that variable number is not an array index. It’s assigned the value of the array element for the current loop iteration.

For each loops and the auto keyword

Because element_declaration should have the same type as the array elements, this is an ideal case in which to use the auto keyword, and let C++ deduce the type of the array elements for us.

Here’s the above example, using auto:

For-each loops and references

In the for-each examples above, our element declarations are declared by value:

This means each array element iterated over will be copied into variable element. Copying array elements can be expensive, and most of the time we really just want to refer to the original element. Fortunately, we can use references for this:

In the above example, element will be a reference to the currently iterated array element, avoiding having to make a copy. Also any changes to element will affect the array being iterated over, something not possible if element is a normal variable.

And, of course, it’s a good idea to make your element const if you’re intending to use it in a read-only fashion:

Rule: In for-each loops element declarations, if your elements are non-fundamental types, use references or const references for performance reasons.

Rewriting the max scores example using a for-each loop

Here’s the example at the top of the lesson rewritten using a for each loop:

Note that in this example, we no longer have to manually subscript the array. We can access the array element directly through variable score.

For-each loops and non-arrays

For-each loops don’t only work with fixed arrays, they work with many kinds of list-like structures, such as vectors (e.g. std::vector), linked lists, trees, and maps. We haven’t covered any of these yet, so don’t worry if you don’t know what these are. Just remember that for each loops provide a flexible and generic way to iterate through more than just arrays.

For-each doesn’t work with pointers to an array

In order to iterate through the array, for-each needs to know how big the array is, which means knowing the array size. Because arrays that have decayed into a pointer do not know their size, for-each loops will not work with them!

Similarly, dynamic arrays won’t work with for-each loops for the same reason.

Can I get the index of the current element?

For-each loops do not provide a direct way to get the array index of the current element. This is because many of the structures that for-each loops can be used with (such as linked lists) are not directly indexable!


For-each loops provide a superior syntax for iterating through an array when we need to access all of the array elements in forwards sequential order. It should be preferred over the standard for loop in the cases where it can be used. To prevent making copies of each element, the element declaration should ideally be a reference.

Note that because for each was added in C++11, it won’t work with compilers that don’t have support for C++11.


This one should be easy.

1) Declare a fixed array with the following names: Alex, Betty, Caroline, Dave, Emily, Fred, Greg, and Holly. Ask the user to enter a name. Use a for each loop to see if the name the user entered is in the array.

Sample output:

Enter a name: Betty
Betty was found.
Enter a name: Megatron
Megatron was not found.

Hint: Use std::string as your array type.

1) Show Solution

6.13 -- Void pointers
6.12 -- Member selection with pointers and references

200 comments to 6.12a — For-each loops

  • leafblower

    is there a reason the examples are using references for int despite the rule saying to do the exact opposite

  • Asgar


    About this rule:
    "Rule: In for-each loops element declarations, if your elements are non-fundamental types, use references or const references for performance reasons."

    Does it mean that the scope of the declared variable in a for-each loop is only a single iteration of the loop and that the declaration statement is re-executed before each iteration?

    As I understand, once a reference variable is initialized it cannot be forced to refer to something else.

  • Bad_at_Coding

    I don't really think that the thing with the namespace was a smart one.

    • * Don't use abbreviations unless their meaning is obvious (without context).
      * It's easier to store @list_names in all lower/upper case. That way you don't have to have a special handling for the first letter. Also, @std::tolower, @std::toupper.
      * @checkName could return directly once the name was found. That way you don't need @found. Also, @std::find.
      * @isFound: Inconsistent naming

  • Son teaches father :)
    Python teaches C++

  • Hakan

    it works when we change it as follows.

  • Alex A


    decided to go a little further with the quiz on this one and make it continue until the user decided they had checked all the names they needed to check. It appears to be working as intended so just looking for any pointers/tips/bits i could do better:

    thanks in advance!

    • * Line 30 cannot be true. Replace the do-while-loop with a while(true) loop
      * @getTryAgain: The return value is unused. The reference to @tryAgain is overly complex. @getTryAgain should return a bool and not take any parameters.
      * Line 36: Use uniform initialization (Remove the equals-sign)
      * Line 39: @std::string's default constructor is faster than it's const char* constructor. Remove the quotation marks, leaving empty curly brackets.
      * Line 52: Don't compare booleans to false/true

  • magaji::hussaini

    So if element_declaration in forEach loop is a reference, it is handled differently since normal references cant be reassigned(default const ptr) RIGHT?

  • Jack

    thanks nascardriver.
    I'm looking forward to being able to actually measure the efficacy of my code, speed v mem used v ugliness? at the moment I have no way of comparing different versions.

    • > speed
      Lesson 8.16

      > mem used
      Process manager.
      With programs as small as the ones on learncpp you won't see much. This will get more important when you're writing big projects. In your previous code you allocated 4 bytes even though you might not need them. That's something you have to notice by looking at the code as you're not going to be able to see a big enough difference at run-time.

      > ugliness
      One person will think of it as pretty and other will hate it. Consistency is what you should be going for. Your code style might be weird, but make it the same weirdness all the way through.

  • Jack

    Hi chaps, great site.
    comments on my solution gratefully received.

  • Gili

    I think the examples in this page are a bit misleading. I can see the benefit of using references instead of copy-by-value when looping over complex types like classes, but how can setting a reference to an int be faster than setting the int itself? A reference has the same (or greater) number of bytes than the fundamental type being references.

    I suggest making this distinction in the tutorial.

    • Alex

      Updated the summary rule to read:

      Rule: In for-each loops element declarations, if your elements are non-fundamental types, use references or const references for performance reasons.

      Thanks for the feedback!

  • Kio

    My 2 cents,

  • My solution

  • Dixit Singla

    It will be great if you please explain how to read multi dimensional arrays using for each loop.
    If already added in the later chapters then okay as I have yet to read the later topics.

  • Baschti

    Why can copying array elements be expensive?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]