开发者

Upper Bound in FOR loop does not get altered in loop,Why?

I am t开发者_StackOverflow社区rying to change the value of upper bound in For loop ,but the Loop is running till the upper bound which was defined in the starting.

According to logic loop should go infinite, since value of v_num is always one ahead of i,But loop is executing three time.Please explain

This is the code

    DECLARE
    v_num number:=3;
    BEGIN
        FOR i IN 1..v_num LOOP
           v_num:=v_num+1;
           DBMS_OUTPUT.PUT_LINE(i ||'  '||v_num);
     END LOOP;
    END;
Ouput Coming

    1  4
    2  5
    3  6


This behavior is as specified in the documentation:

FOR-LOOP
...
The range is evaluated when the FOR loop is first entered and is never re-evaluated.

(Oracle Documentation)


Generally, FOR loops would be fixed iterations

For indeterminate looping, use WHILE

This isn't Oracle specific, and why there are separate looping constructs.


While it is generally considered a bad idea to change the loop variable's value, sometimes it seems like the only way to go. However, you might find that loops are optimized, and that might be what is happening here.


There's nothing preventing the language designers from saying "The upper bound of the for loop is evaluated only once". This appears to be the rule that plsql is following here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜