Friday, March 16, 2012

A simple For..Loop Puzzle

What is the output of below pl/sql block?

        var1 number(2) :=1;
        var2 number(2) :=5;
      for i in var1..var2 loop
           dbms_output.put_line( 'i,var2: ' || i || ','||var2);
           if i= 3 then
                var2 :=7;
           end if;
      end loop;

The output of the above pl/sql block is,
i,var2: 1,5
i,var2: 2,5
i,var2: 3,5
i,var2: 4,7
i,var2: 5,7

Surprised?? One can argue that the loop should have been continued until i reaches the new value of var2, which is 7. The below extract from oracle documentation will silent the argument,

Numeric FOR_LOOP loops iterate over a specified range of integers. The range is part of an iteration scheme, which is enclosed by the keywords FOR and LOOP.

The range is evaluated when the FOR loop is first entered and is never re-evaluated. The loop body is executed once for each integer in the range defined by lower_bound..upper_bound. After each iteration, the loop index is incremented.

No comments: