Version 4 of Brace your expr-essions

Updated 2003-10-20 15:31:27

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 +]

KPV: Braced expressions also don't work when you do negation in the lazy way:

  set n1 -3
  set n2 -$n1
  expr {2 + $n2} ;# error
  expr 2 + $n2   ;# ok