Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type is in the range for loop?

Tags:

c++

c++11

#include <vector>
#include <iostream>

int main()
{
    std::vector< int > v = { 1, 2, 3 };
    for ( auto it : v )
    {
        std::cout<<it<<std::endl;
    }
}

To what is auto expanding? Is it expanding to int& or int?

like image 428
BЈовић Avatar asked Nov 25 '11 13:11

BЈовић


People also ask

What is the range of loop?

To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Does for loop work on range?

for loops repeat a block of code for all of the values in a list, array, string, or range() . We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .

What data type is best for a loop?

To be on the safer side its good to take a loop variable as 'int'. One more thing, if you are using such a loop for something like a Delay_ms() function, and if you try to restrict the loop variable to char , you will have to have nested loops, or call the same Delay_ms() function again and again.

What is I in for i in range?

Python for i in range helps iterate a series of values inside the range function. Where the value “i” is a temporary variable used to store the integer value of the current position in the range of the for loop.


1 Answers

It expands to int. If you want a reference, you can use

for ( auto& it : v )
{
    std::cout<<it<<std::endl;
}

According to the C++11 standard, auto counts as a simple-type-specifier [7.1.6.2], thus the same rules apply to it as to other simple-type-specifiers. This means that declaring references with auto is no different from anything else.

like image 135
Tamás Szelei Avatar answered Oct 09 '22 20:10

Tamás Szelei