CS.UNINIT.LOOP_COUNTER

Uninitialized loop counter in for statement.

Loop counter not declared in initialization expression in for statement.

Vulnerability and risk

Unless there is an explicit reason, counter variables should be declared and initialized in the initialization expression of a for statement, to prevent unintended loop counter reuse.

Mitigation and prevention

Unless there is an explicit reason, counter variables are declared and initialized in the for statement's initialization expression.

Example

Copy
  namespace kmcustom
  {
      class C05
      {
          public void testOK()
          {
              for (int i = 0; i < 5; i++)
              {
                  //do something
             }
         }
 
         public void testNG()
         {
             int i = 0;
             for (i = 0; i < 5; i++) //NG
             {
                 //do something
             }
 
         }
         public void testNG2()
         {
             int i = 0;
             for (; i < 5; i++) //NG
             {
                 //do something
             }
 
         }
 
 
     }
 }