問題描述
在while循環中繼續的奇怪行為 (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?
參考解法
方法 1:
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).
(by Vasilis、user271608)