Область действия переменной может быть уменьшена в функции в c - PullRequest
1 голос
/ 05 апреля 2020

Итак, у меня есть эта функция, и не имеет значения, что она делает, важно то, что я использую cppcheck для проверки ошибок, и я получаю это сообщение:

сообщение:

(style) The scope of the variable 'i' can be reduced. Warning: Be careful when fixing this message, especially when there are inner loops. Here is an example where cppcheck will write that the scope for 'i' can be reduced:
void f(int x)
{
    int i = 0;
    if (x) {
        // it's safe to move 'int i = 0;' here
        for (int n = 0; n < 10; ++n) {
            // it is possible but not safe to move 'int i = 0;' here
            do_something(&i);
        }
    }
}
When you see this message it is always safe to reduce the variable scope 1 level.

Функция :

void p(int idp, int price)
{
   int i = 0;
   if ((indentify_prod(sistem,idp) == 1) && (price > 0)) /* product exists in the sistem*/
   {
      sistem[idp].price = price;
      while (i <500)
      {
          if (sistem[idp].ident == sistem_orders[i].set_prod[idp].ident)
          {
              if ((product_in_order(i,sistem_orders,idp) == 1) && (product_in_system(idp) == 1)){
              sistem_orders[i].set_prod[idp].price = price;
              }
          }
          i++;
      }
   }
   else 
   {
      printf("Impossivel alterar preco do produto %d. Produto inexistente.\n",idp);
   }
}

Я действительно не понимаю это предупреждение, как уменьшить область, что это значит? Я пытался уменьшить значение с 500 до 200, но все равно выдает ту же ошибку, и я не понимаю, почему.

Серьезно, любая помощь будет признательна.

1 Ответ

0 голосов
/ 05 апреля 2020

Простой пример:

void foo()
{
  int somevar;
  for (int j = 0; j < bar; j++)
  {
    // do something with somevar
  }

  // more code not using somevar
}

Вы можете переписать это так:

void foo()
{
  for (int j = 0; j < bar; j++)
  {
    int somevar;  // you can declare somevar here because it's
                  // not used outside the scope of this for loop

    // do something with somevar
  }

  // more code not using somevar
}
...