Range-based for loop in C++

In this blog post, I will explain the range-based for loop with the help of example code. The range-based for loop is introduced in C++11.

It executes a for loop over a range and is more readable equivalent to the traditional for loop.  See the below syntax for the range-based for loop.

Syntax:

for ( for-range-declaration : expression )
   loop statement

Parameters :

range_declaration:

A declaration of a named variable, whose type is the type of the element of the sequence represented by range-expression, or a reference to that type. Often uses the auto specifier for automatic type deduction.

expression:

Any expression that represents a suitable sequence or a braced-init-list.

loop_statement :

Any statement, typically a compound statement, is the loop’s body.

 

Let’s see an example code to understand how you can use the range-based for loop for an array and vector in C++.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    cout << "Access array with ranged base for loop " <<endl;

    // Basic array of 5-element integer.
    int arr[] = { 10, 20, 30, 40, 50};

    // Range-based for loop to iterate through the array.
    // Access by value using a copy declared as a specific type.
    for( int tmpArr : arr )
    {
        cout << tmpArr << " ";
    }
    cout << endl;

    // The auto keyword causes type inference to be used. Preferred.
    // Copy of 'arr', almost always undesirable
    for( auto tmpArr : arr )
    {
        cout << tmpArr << " ";
    }
    cout << endl;

    for( auto &tmpArr : arr )   // Type inference by reference.
    {
        // Observes and/or modifies in-place. Preferred when modify is needed.
        cout << tmpArr << " ";
    }
    cout << endl;

    for( const auto &tmpArr : arr )   // Type inference by const reference.
    {
        // Observes in-place. Preferred when no modify is needed.
        cout << tmpArr << " ";
    }
    cout << endl  <<endl;

    cout << "Access vector with ranged base for loop " <<endl;
    // Create a vector object that contains 4 elements.
    vector<int> v {10, 20, 30,40};

    // Range-based for loop to iterate through the vector, observing in-place.
    for( const auto &vec : v )
    {
        cout << vec << " ";
    }
    cout << endl;
}

Output:

Access array with ranged base for loop
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50
10 20 30 40 50

Access vector with ranged base for loop
10 20 30 40

 

How does the range-based loop work in C++?

The range-based for statement,

for ( range_declaration : range_expression)

    loop_statement

is equivalent to (since C++20)

{
    auto &&range = range_expression);
    auto begin = begin-expr ;
    auto end = end-expr ;
    for( ; begin != end ; ++begin )
    {
      range_declaration = * begin ;
      loop_statement
    }
}

The above code, range_expression is evaluated to determine the sequence or range to iterate. Also begin-expr and end-expr are determined as follows:

  • If the range_expression is an expression of array type R, begin-expr and end-expr are; range
    and range + N, respectively, where N is the array bound. If R is an array of unknown bound or an array of incomplete type, the program is ill-formed;
  • If the range_expression is an expression of class type C, and searches in the scope of C for the names begin and end each finds at least one declaration, begin-expr, and end-expr are range.begin() and range .end(), respectively;
  • Otherwise, begin-expr and end-expr are begin(range ) and end(range ), respectively, where begin and end undergo argument-dependent lookup.

Note: Just like a traditional for loop, a range-based for loop terminates when one of these in the statement is executed: a break, return, or goto to a labeled statement outside the range-based for loop. A continue statement in a range-based for loop terminates only the current iteration.

 

Advantages and Disadvantages of Range-based for Loop:

The following are some advantages and disadvantages of range-based for loop. So let’s first start with the advantage.

Advantage:

  • Easy and Convenient to use.
  • You only need to use two expressions while in traditional for loop three.
  • The range-based for loop gives you the elements.
  • You don’t need to calculate the count of iterations. The loop automatically handles that. It knows the beginning and end elements of the containers
  • The auto keyword is typically used to determine the data type of container elements.
  • You don’t need to worry about the termination condition and increment or decrement operations in the loop syntax.
  • If you want to iterate through a complete array or a collection then, it is a good choice.

Disadvantage:

  • Its syntax is cleaner and more universal, but you can’t execute the code in the loop for a specified range different than from begin() to end(). That means, unlike traditional loops, you can not target any specific index or element.
  • It iterates over the whole array using the iterator, not the index, so you can not skip skipping a value at any specific index or a group of indices can not be done.

 

Recommended Articles for you: