开发者

weird behaviour of continue in while loop

I'm fairly new in TCL programming and by going through the basics I encountered the following code snippet:

set x 0;
while "$x < 3" {
    set x [expr $x + 1]
    if {$x >6} break;
    if "$x > 2" continue;
    puts "x is $x"; 
    }
puts "exited second loop with X equal to $x\n"

When executed, the result is the following:

x is 1

x is 2

exited second loop with X equal to 7

What surprises me is that when the continue command is executed the while loop test (x<3) doesn't seem to be evaluated. However in the tcl manpages state that "A continue statement within body will stop the execution of the code and the test will开发者_运维知识库 be re-evaluated."

What am I missing?


Because you have used quotes in "$x < 3", you are evaluating that condition only once: the first time it is seen by the tcl interpreter, permanently making the test "0 < 3". Since it's always true, you only exit the body of the while loop when you [break].

if you use braces {} instead of quotes " " for the while condition, that test is evaluated only by the while loop itself, and not by the substitution pass of the tcl interpreter, and performs as you would expect.

Rule of thumb: always use {} in the test of if/while/for etc (unless the first mentioned behavior is what you are looking for).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜