Go back to Richel Bilderbeek's homepage.

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

 

 

 

(C++) for

 

Keyword for starting a for-loop.

 

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

 

For loop syntax

 

 

for ( /* initialization */ ; /* breaking condition */ ; /* after-loop operation */ )

{

  // The code block that will be repeated while the breaking condition is true

}

 

 

For loop example

 

 

#include <iostream>

 

int main()

{

  for (

    int i=0; //Create an in-loop integer variable called i

    i!=10;   //Enter loop while i!=10

    ++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!

5: Hello!

6: Hello!

7: Hello!

8: Hello!

9: Hello!

 

 

References

[0]         Bjarne Stroustrup. The C++ Programming Language (3rd edition). ISBN: 0-201-88954-4. Chapter 18.12.1 : 'Prefer algorithms over loops'

[1]         Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 84: 'Prefer algorithm calls to handwritten loops.'

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.