Main Content

Tcl - the danger of square brackets in a while command

Archive - Originally posted on "The Horse's Mouth" - 2011-03-02 07:58:35 - Graham Ellis

In Tcl, every statement is a command - with the parameters separated by spaces. Elements which are written in square brackets are commands which are evaluated before the rest of the statement, and elements which are written in curly braces are deferred - held back - and are only evaluated (if at all) after the statement itself is has been initiated.

Let's see what that means for a while command - full source [here]:

  while {$hunger > 0} {
The test (deferred block) is passed into the while command and will be evaluated each time the condition needs to be checked as the program loops. An expr is assumed by while, so there's no need for you to add one yourself. You could have written
  while {[expr $hunger > 0]} {
and that would function in the same way.

However - if you use square brackets in the condition of a while command, without deferring them, the condition will be evaluated once only before the loop block is evaluated for the first time. And if that evaluation is true, you'll then have a block which repeats forever - an infinite loop - which you'll have to break out of with a break command, or a return:
  while [expr $hunger > 0] {

Once I've explained this to you, it's probably quite clear - but the code in that last example looks confusing and I would advise against using the structure for a while loop. If you're writing a conditional such as an if, you may use square brackets, since the condition is only going to be evaluated once anyway.

Example written on yesterday's Tcl course.