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

About vineethkartha

Hi, I am Vineeth Kartha, I hold a Masters degree in Embedded Systems from BITS Pilani, Goa Campus. I currently work as a Software Developer. I am A free software promoter and electronics hobbyist. In my free time I do a little bit of birding and Wildlife photography. I love travelling, reading and blogging.

Posted on February 2, 2016, in Technical. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: