I'm trying to figure out why in this example the while loop keeps going on indefinitely. The explanation given is

If test is placed within quotes, the substitution phase will replace any variables with their current value, and will pass that test to the while command to evaluate, and since the test has only numbers, it will always evaluate the same

I know that normally you would just use curly braces instead of quotes but I want to understand why double quotes are not used. I also understand that double quotes will substitute the values while the curly braces do not.

set x 0 while "$x < 5" { set x [expr {$x + 1}] if {$x > 7} break if "$x > 3" continue puts "x is $x" } 

when I print x within the loop I can see it increment so in the case x is 5. I expect the "set x" line to change the value to 6 and will skip the break line. I expect the x > 3 line to pass how come when it checks "$x < 5" that "6 < 5" still gets interpreted as true?

1

1 Answer

When tcl tries to evaluate the while statement, the first thing it does is split the statement into words, and substitute anything that's in double quotes or square brackets. Data in curly braces is not substituted.

This happens before the while command is called. After this round of substitution, the result of all of the substitutions is passed to the while command as arguments.

Thus, the while statement is given two arguments:

  1. 0 < 5
  2. everything inside the curly braces

while sees a static condition that never changes so the loop runs forever.

You should use curly braces so that tcl passes the condition to the while command on each iteration:

while {$x < 5} { ... } 

With the above, while gets the following arguments:

  1. $x < 5
  2. everything inside the curly braces

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.