Unreachable code in for loop increment?

congusbongus picture congusbongus · Jan 15, 2015 · Viewed 8k times · Source

I'm getting a C4702: unreachable code warning in a for loop; the strange thing is that - by breaking apart the components inside the parens - the warning points to the increment part. Here's a sample program that demonstrates this error:

int main()
{
    int foo = 3;
    for (int i = 0;
        i < 999;
        i++)    // warning on this line
    {
        if (foo == 4);
        {
            break;
        }
    }
    return 0;
}

I can't figure out what's wrong with this line, because the for loop looks very straight-forward.

Answer

congusbongus picture congusbongus · Jan 15, 2015

You have a stray semicolon in your if-statement:

if (foo == 4);

Recall that for loops have the following structure:

for (initialisation; condition; increment/decrement)
    statement

Execution will proceed in the following order:

  1. initialisation
  2. condition; if false then end
  3. statement
  4. increment/decrement
  5. Go to step 2

If the compiler is warning about the increment/decrement being unreachable, it means that something before it is causing execution to always skip it - in this case, the stray semicolon causes the break to always execute, jumping out of the loop prematurely.