Monthly Archives: February 2016

Range Based For Loops in C++11


Here is a short post on the range based for loops in C++. I recently learned about range based for loops in C++11 standards. These are nothing but easier constructs on writing loops. You no longer have to write:

for(initialization;condition;update)

The syntax is:

for(declaration:expression)

Although this looks like a very simple feature there are a few things to keep in mind while using the range based for loops.

Lets take a look at a simple piece of code:

#include<iostream>
int count(int array[100])
{
 int total=0;
 for(auto num:array)
 total++;
 return total;
}
int main()
{
 int array={1,2,3,4,5};
 std::cout<<count(array)<<"\n";
 return 0;
}

If you compile the above code it throws compiler errors.

The same code will work if ‘array’ is a local variable in the main.
This baffled me for quite sometime and it is a friend of mine who explained to me why this happens.

This is how a range based for loop works:

It starts from the beginning of the array and travels till the end. So it needs the iterators to traverse the given array. In the code provided above ‘array’ is passed as a pointer and it does not have any iterator or boundary information. So in my original code if I pass ‘array’ as a ‘std::vector<int>array’, the code works fine.

Hope this will help someone else who is stuck. To know more in depth about how range based for loops work in C++, refer to the link provided below:
http://en.cppreference.com/w/cpp/language/range-for

Advertisements
%d bloggers like this: