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

Viewed 1233

So i have this function and it doesnt matter what it does what matters is that im using cppcheck to check on errors and i get this message:

message:

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

I really dont understand this warning like reduce the scope what does this mean? Ive tried to reduce the value of 500 to 200, but it still gives the same error and i dont understand why.

Seriously any help would be appreciated.

2 Answers

Simple example:

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

  // more code not using somevar
}

You can rewrite this like this:

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
}

You can move it inside the if to reduce the scope of i.

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