Tutorials  /  Linux Basics

The foreach loop in C++

Ccentron Redaktion · January 2024 ·5 min read ·Linux Basics, Tutorial

Introduction

The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator. So let us dig into the respective foreach loop structure.

VM

Matching infrastructure at centron

No hardware needed to follow along: ccloud³ VMs with full root access start at €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

Working of the foreach loop in C++

So basically a for-each loop iterates over the elements of arrays, vectors, or any other data sets. It assigns the value of the current element to the variable iterator declared inside the loop. Let us take a closer look at the syntax:

Code
for(type variable_name : array/vector_name)
{
    loop statements
    ...
}

As we can see:

  • During the loop initialization, the elemental variable declaration is the part where we need to declare the variable which will iterate over the array or vector.
  • Here, the type is the data type of the variable_name
  • array/vector name is the name of the respective data set over which the loop will iterate,
  • loop statements are the different operations which the user can choose to perform over the corresponding elements with the use of the iterating variable.

Note: It is suggested to keep the data type of the variable the same as that of the array or vector. If the data type is not the same, then the elements are going to be type-casted and then stored into the variable.

Examples of foreach loop

1. Example of foreach loop for Arrays in C++

The code given below illustrates the use of the for-each loop in C++,

Code
#include
using namespace std; 
int main() 
{ 
    int arr[]={1,2,3,4,5};   //array initialization
    cout<<"The elements are: ";
    for(int i : arr)
    {
    	cout<<i<<" ";
    }
    return 0;
}

Output:

Code
The elements are: 1 2 3 4 5

Let’s break down the code and look at it line-by-line:

  • An array arr[] is initialized with some values {1 , 2 , 3 , 4 , 5}
  • Inside the loop structure, ‘i’ is the variable that stores the value of the current array element
  • arr is the array name which also serves as the base address of the respective array
  • As we can see, printing ‘i’ for each iteration gives us the corresponding array elements in contrast to the array indices in case of normal for loop

Please note: While declaring the variable ‘i’ we could also use the auto datatype instead of int. This ensures that the type of the variable is deduced from the array type, and no data type conflicts occur.

For example:

Code
#include
using namespace std; 
int main() 
{ 
    int array[]={1,4,7,4,8,4};
    cout<<"The elements are: ";
    for(auto var : array)
    {
    	cout<<var<<" ";
    }
    return 0;
}

2. Example of foreach loop for Vectors in C++

The following code illustrates the use of the for-each loop for iterating over a vector.

Code
#include
#include
using namespace std; 
int main() 
{ 
    vector vec={11,22,33,44,55,66};
    cout<<"The elements are: ";
    for(auto var : vec)
    {
    	cout<<var<<" ";
	}
    return 0;
}

The for-each loop for vector works in the same way as it does for an array. Furthermore, the only differences are the vector declaration, initialization and the different operations that can be performed over it.

Advantages and Disadvantages of the foreach loop in C++

1. Advantages of foreach loop

  • It eliminates the possibility of errors and makes the code more readable.
  • Easy to implement
  • Does not require pre-initialization of the iterator

2. Disadvantages of foreach loop

  • Cannot directly access the corresponding element indices
  • Cannot traverse the elements in reverse order
  • It doesn’t allow the user to skip any element as it traverses over each one of them

Conclusion

The foreach loop in C++ has its own pros and cons. The code is easy to read but it restricts some of the actions that the normal for loop offers. Hence, it completely depends on the user what he/she wants the loop to perform and choose accordingly -  A Complete Guide

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Linux Basics
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren