TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
C++ Coding Standard
Search

Rule:  CFL#009Checked automatically with code checker

Synopsis:Never use continue in a nested loop
Language:C++
Severity Level:9
Category:Control Flow


Description:

The "continue" statement is used to force the next iteration of a loop to take place. This can help to make loops in code more readable. Compare for instance the following code containing "continue" statements:

for(object_id_t id : proc_list)
{
  object* obj = find_object(id);
  if(!obj)
    continue;
 
  if(obj->is_active())
    continue;
         
  time_t elapsed = now() - obj->begin;
  if(elapsed < timeout)
    continue;
 
  ...
}

with the semantically equivalent code without "continue" statements:

for(object_id_t id : proc_list)
{
  object * obj = find_object(id);
  if(obj)
  {
    if(!obj->is_active())
    {
      time_t elapsed = now() - obj->begin;
      if(elapsed >= timeout)
      {
        ...
      }
    }
  }
}

The second example is less readable because nested "if" statements are needed.

But the "continue" statement also has a downside. Since "continue" is tied to its directly enclosing loop, its meaning can change unexpectedly if the "continue" statement is moved. The compiler will not warn you about this. Consider for example the following code:

for (int i = 0; i < max; i++) {
  ...
  for (int j = 0; j < max; j++) {
    ...
    some code
      continue; // somewhere a little bit hidden
    some other code
    ...
  }
}

and suppose some lines of code are moved to the outer loop:

for (int i = 0; i < max; i++) {
  ...
  some code
    continue; // somewhere a little bit hidden
  some other code
  ...
  for (int j = 0; j < max; j++) {
    ...
  }
}

Now all of a sudden the inner loop is not executed any more if the "continue" statement is reached. If this is not intended it might take a lot of debugging effort to understand why this happened. So it is better to avoid "continue" statements in nested loops.