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 following for-each example, 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:


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 or get its size. We can access the array element directly through variable score. The array has to have size information. An array that decayed to a pointer cannot be used in a for-each loop.

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.

Quiz time

This one should be easy.

Question #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_view as your array type.

Show Solution

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

263 comments to 6.12a — For-each loops

  • Mert

    Hello nascardriver and Alex,

    #include <iostream>
    #include <vector>

    int main()
        std::vector fibonacci{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 }; // note use of std::vector here rather than a fixed array

        for (const auto &number : fibonacci)
            std::cout << number << ' ';

        std::cout << '\n';

        return 0;

    In this code why did whe use "const auto &number" for for-each loop what does it means because, I also saw this in the summary section but didn't get the idea why we use this instead of "auto number : fibonacci" is it related to length of the dynamic array could you give me some insight about it? Have good day/night.

    • nascardriver

      That example shouldn't use a reference. I update the lesson. References are used to prevent copies of large types. Since `fibonacci` is a vector of `int`, and `int` is a type that's fast to copy, no reference should be used.

  • Just thought I'd share my implementation of the quiz. I used a vector instead.

    • nascardriver

      Congratulations on solving this quiz!
      Global variables are evil, and unnecessary in this example. `names` can be moved into `checkIfNameIsFoundInListAndNotifyUser`.

  • Vova

    I just noticed a rule suggested in the "For each loops and references" section:
    Rule: In for-each loops element declarations, if your elements are non-fundamental types, use references or const references for performance reasons.

    But in the examples above didn't we use int? Isn't int a fundamental data type?

    • nascardriver

      You're right! `int` is a fundamental type and should be copied rather than referenced. I updated the example to use `std::string`. Thanks!

  • Siva


    Can you please clarify below point.

    How does for each loop know size of linked list in advance?


    • nascardriver

      Hi Siva!

      The range-based loop doesn't know the length. It keeps looping until it finds the end of the list.

      Where `list.first` is the first element, `list.end` is the end marker, and `` is the next element in the list.

      A lesson about this is in the making. Look up "iterators" for more information.

  • Luiz Carlos

    I have a question regarding the 'nameInput' variable I defined above the infinite loop. Where is the best place for it to be defined? Inside or outside the loop?

    Also, is this an efficient way of accomplishing what I did?

    • nascardriver

      Outside the loop is probably faster, because the string can re-use memory.
      Generally, inside the loop is better to limit the scope.

      Efficiency really isn't a concern when you're blocking to ask for user input, as that's what takes up the majority of time.
      A minor performance improvement is to not use `"text" << '\n'` but instead `"text\n"`. If you don't like that, you can also do `"text" "\n"`. This will concatenate the strings at compile-time but keep a space between the text and the line break.

  • alfonso

    Pretty much the same solution.

    • Hello alfonso!

      Unless you have a specific reason to manually set the array's length (Line 24), you should n't do so. If you create the array first and then get its length, if at all, your code is easier to update. In this case, you can remove `len` and your program will work just fine.
      Your code looks good otherwise, keep it up :)

  • Alex

    It might be a good idea to change the title of this article; foreach loops are more commonly called "range-based for loops" in C++. "Foreach" is more of a C# term.

  • pibaereg

    Is it okay to simply add a return statement like this? Or should I avoid doing this? Thanks!

    • It's best to avoid `return` and `break`. If you think you need to `return` from a loop, move your code into a separate function, eg. `arrayContains`. Then call `arrayContains` from `main`. The `return` in `arrayContains` is easily spotted, not so much the `return` in `main`.

Leave a Comment

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