A range-for loop in C++

The so-called range-based for loop appeared in the C++ 11 standard, together with the auto keyword gives us a very powerful and idiomatic way of looping over things.

Let’s start with a simple array.

#include <iostream>

int main() {
    int odd_data[] = {1, 3, 5, 7, 9};

    for (auto x : odd_data)
        std::cout << x << "\n";
}

Here, the for loop goes over all the elements of the odd_data array, and you do not need to worry about the size of the array. This makes the C++ code very clean but it remains as efficient as the more classical approach with the loop counter.

Notices the use of auto in the declaration of x. Indeed, the compiler knows the type of the array elements, so there’s no need to type it again.

You would not be surprised that the code works with STL vectors with no change. Here is the same example where the array is replaced with a vector:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> odd_data {1, 3, 5, 7, 9};

    for (auto x : odd_data)
        std::cout << x << "\n";
}

To compile the program, instruct the compiler to use the proper C++ standard:

g++ -std=c++11 test.cpp 

One thought on “A range-for loop in C++”

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code