>
>
>
V711. It is dangerous to create a local…


V711. It is dangerous to create a local variable within a loop with a same name as a variable controlling this loop.

The analyzer has detected a variable declared inside a loop body so that its name coincides with that of the loop control variable. Although it's not always critical for for and foreach (C++11) loops, it is still a bad programming style. For do {} while and while {} loops, however, it's much more dangerous as the new variable inside the loop body may accidentally get changed instead of the variable in the loop condition.

An example:

int ret;
....
while (ret != 0)
{
  int ret;
  ret = SomeFunctionCall();
  while (ret != 0)
  {
    DoSomeJob();
    ret--;
  }
  ret--;
}

In this situation, an infinite loop may occur since the external variable 'ret' in the loop body is not changed at all. An obvious solution in this case is to change the name of the internal variable:

int ret;
....
while (ret != 0)
{
  int innerRet;
  innerRet = SomeFunctionCall();
  while (innerRet != 0)
  {
    DoSomeJob();
    innerRet--;
  }
  ret--;
}

The analyzer doesn't generate the V711 warning for each and every case when a variable has the same name as that used in the loop body. For example, below is a code sample that won't trigger the warning:

int ret;
....
while (--ret != 0)
{
  int ret;
  ret = SomeFunctionCall();
  while (ret != 0)
  {
    DoSomeJob();
    ret--;
  }
}

Neither does the analyzer generate the warning when suspicious variables are obviously of non-corresponding types (say, a class and a pointer to int). There are much fewer chances to make a mistake in such cases.

This diagnostic is classified as:

  • CERT-DCL01-C

You can look at examples of errors detected by the V711 diagnostic.