在while循環中繼續的奇怪行為 (weird behaviour of continue in while loop)


問題描述

在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 Vasilisuser271608)

參考文件

  1. weird behaviour of continue in while loop (CC BY-SA 3.0/4.0)

#continue #while-loop #TCL






相關問題

skrip shell: loop bersarang dan lanjutkan (shell script : nested loop and continue)

syntaxError:“繼續”在循環中不正確 (syntaxError: 'continue' not properly in loop)

php continue - 替代方式? (php continue - alternative way?)

Python 中的歐拉 #4 (Euler #4 in Python)

if-continue vs 嵌套 if (if-continue vs nested if)

如何返回上一個 while 循環? (How do I return to the previous while loop?)

php foreach 繼續 (php foreach continue)

在while循環中繼續的奇怪行為 (weird behaviour of continue in while loop)

是否可以使用 'yield' 來生成 'Iterator' 而不是 Scala 中的列表? (Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

rand() 函數後繼續指令的問題 (Problem with continue instruction after rand() function)

在tictactoe遊戲中重複輸入錯誤 (Error in repeating input in a tictactoe game)







留言討論