簡體   English   中英

變量的 scope 可以在 c 中減少 function

[英]The scope of the variable can be reduced in a function in c

所以我有這個function,它做什么並不重要,重要的是我使用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.

Function:

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);
   }
}

我真的不明白這個警告,比如減少 scope 這是什么意思? 我試圖將 500 的值減少到 200,但它仍然給出相同的錯誤,我不明白為什么。

認真的任何幫助將不勝感激。

簡單的例子:

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
}

您可以將其移動到if中以減少i的 scope 。

void p(int idp, int price)
{
>>>int i = 0; ***** REMOVE THIS LINE *****
   if ((indentify_prod(sistem,idp) == 1) && (price > 0)) /* product exists in the sistem*/
   {
>>>>>>int i = 0; ***** ADD THIS LINE *****
      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);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM