Skip to content

G-4390: Avoid use of unreferenced FOR loop indexes.

Major

Efficiency

Reason

If the loop index is used for anything but traffic control inside the loop, this is one of the indicators that a numeric for loop is being used incorrectly. The actual body of executable statements completely ignores the loop index. When that is the case, there is a good chance that you do not need the loop at all.

Example (bad)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
declare
   l_row          pls_integer;
   l_value        pls_integer;
   co_lower_bound constant simple_integer           := 1;
   co_upper_bound constant simple_integer           := 5;
   co_row_incr    constant simple_integer           := 1;
   co_value_incr  constant simple_integer           := 10;
   co_delimiter   constant types_up.short_text_type := ' ';
   co_first_value constant simple_integer           := 100;
begin
   l_row   := co_lower_bound;
   l_value := co_first_value;
   <<for_loop>>
   for i in co_lower_bound..co_upper_bound
   loop
      sys.dbms_output.put_line(l_row
         || co_delimiter
         || l_value);
      l_row   := l_row + co_row_incr;
      l_value := l_value + co_value_incr;
   end loop for_loop;
end;
/

Example (good)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
declare
   co_lower_bound constant simple_integer           := 1;
   co_upper_bound constant simple_integer           := 5;
   co_value_incr  constant simple_integer           := 10;
   co_delimiter   constant types_up.short_text_type := ' ';
   co_first_value constant simple_integer           := 100;
begin
   <<for_loop>>
   for i in co_lower_bound..co_upper_bound
   loop
      sys.dbms_output.put_line(i
         || co_delimiter
         || to_char(co_first_value + i * co_value_incr));
   end loop for_loop;
end;
/