Skip to content
Joël R. Langlois edited this page Oct 30, 2017 · 1 revision

Iteration Rules

Always use the index-driven iteration method, unless you have a simpler iteration mechanism available to you.

Always follow this convention for forward iteration:

for (int i = 0; i < list.size(); ++i)

Always follow this convention for reverse iteration:

for (int i = list.size(); --i >= 0;)

If C++11 is supported across the board, and assuming your container and context work safely with this mechanism, use range-based for:

for (auto* item : listOfMyClass)

Intentional Infinite Loops

Always use the for (;;) convention when creating infinite loops.

This is to avoid a warning about using while (true) or do {} while (true) on some compilers. See MSDN Warning C4127 for more details.

static int update()
{
    for (;;)
    {
        if (shouldShutdown())
            break;

        //update variety of things

        if (somethingBroke())
            return 1;
    }

    return 0;
}

Do/While Loops

Always place while on the next line, after the closing brace of the loop's body.

do
{
    //[...]
}
while (conditionThatOkaysTheLoop)
Clone this wiki locally