Version 3 of Brace your expr-essions

Updated 2003-10-20 13:54:29

KBK closed a follow-up to the comp.lang.tcl newsgroup with the advice that, "Also, it's important always, always to brace your expressions. Don't do

     set a [expr $b / $c]

but rather

     set a [expr { $b / $c }]

Otherwise, your variables may undergo unexpected conversions numeric -> string -> numeric, you can lose precision, your expressions will be much slower, and you can even have security problems:

     # don't run
     set x { [format C:\] }
     set y [expr $x + 3]

"


RS: In the following cases braced expressions don't work:

  • operator in variable (which in most languages is impossible, but Tcl can do):
 set op +
 expr $x $op $y
  • (parts of) expression generated by string manipulation:
 expr [join $intlist +]