Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) for

 

for is a keyword to start a for-loop.

 

Prefer algorithms over loops [1][2]. See Exercise #9: No for-loops to learn how to do so.

 

 

 

 

 

C++98C++11 For loop syntax

 

for ( /* initialization */ ; /* breaking condition */ ; /* after-loop operation */ )
{
  // The code block that will be repeated while the breaking condition is true
}

 

 

 

 

 

C++98C++11 For-loop example

 

#include <iostream>

int main()
{
  for (
    int i=0; //Create an in-loop integer variable called i
    i!=5; //Enter loop while i!=5
    ++i) //After looping, increment i
  {
    std::cout << i << ": Hello!\n";
  }
}

 

The code above generates the following screen output:

 

0: Hello!
1: Hello!
2: Hello!
3: Hello!
4: Hello!

 

 

 

 

 

C++11 Range-based for

 

 

C++11 supports a range-based for:

 

#include <vector>

int main()
{
  std::vector<int> v = { 1,2,3,4,5,6,7,8,9 };
  for (int& i: v)
  {
    i*=i;
  }
}

 

Note that the example initializes the std::vector with an initializer list.

 

Technical note: the code shown did not compile using the G++ 4.4.5 compiler, which is supplied with the Qt Creator 2.0.0 IDE, but is expected to compile in G++ 4.6 [3].

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'
  2. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. 2005. ISBN: 0-32-111358-6. Item 84: 'Prefer algorithm calls to handwritten loops'
  3. GCC page about C++0x support

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict