Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'colon' and 'auto' in for loop c++? need some help understanding the syntax

Tags:

I need some explanation for the following c++ syntax:

for(const auto& ioDev : deviceList) 

given that:

std::vector<Device *> deviceList 

Specifically, I am confused about ':' and the usage of 'auto'?

like image 763
MIbrah Avatar asked Feb 18 '16 19:02

MIbrah


People also ask

What is the syntax of for in loop?

The syntax of for loop in c language is given below: for(Expression 1; Expression 2; Expression 3){ //code to be executed. }

What is a loop explain for loop with syntax and example?

A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.

What is a for loop example syntax?

Example 1: for loop // Print numbers from 1 to 10 #include <stdio.h> int main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } return 0; } Run Code. Output 1 2 3 4 5 6 7 8 9 10. i is initialized to 1. The test expression i < 11 is evaluated.

What is the colon used for in for loop C++?

The meaning of colon in c++ The idea is to loop through each element in the array (or vector, or other iterable). The element variable is each element of the array, moving to the next element at the start of each iteration.


2 Answers

As described in the answer by Chad, your for-loop iterates over your vector, using its begin and end iterators. That is the behavior of the colon : syntax.

Regarding your const auto & syntax: you should imagine what code comes out of it:

// "i" is an iterator const auto& ioDev = *i; 

The expression *i is (a reference to) the type of elements in the container: Device *. This is the deduced type of auto. Because you have const & appended to your auto, the variable ioDev is a const reference to the deduced type (a pointer), as if it were declared this way:

const Device *& ioDev = *i; 

It seems needlessly complicated; if you need just normal iteration (and not e.g. manipulating the address of the pointer, which I think is highly unlikely), use a plain unmodified auto:

for (auto ioDev : deviceList) 

or an explicit type:

for (Device* ioDev : deviceList) 
like image 39
anatolyg Avatar answered Oct 01 '22 05:10

anatolyg


This is a range based for loop, it has the same basic behavior of:

for(auto it = deviceList.begin(); it != deviceList.end(); ++it) {    const auto& ioDev = *it; } 

The range based for loop has quickly become one of my favorite constructs, it's terse and when you need to iterate an entire range, works as well (and as efficiently) as possible.

If you need the other constructs of a typical for loop (say to exit early in some case), then range-based for isn't for that use case.

like image 120
Chad Avatar answered Oct 01 '22 04:10

Chad