Version 6 of Toggling a Boolean Variable

Updated 2002-11-06 16:48:38

proc toggle {v} {

  uplevel [concat set $v \[expr \[set $v\] ^ 1\]]
 }

 % set state 0
 0
 % toggle state
 1
 % toggle state
 0

RS has this alternative:

 proc toggle varName {
     upvar 1 $varName var
     set var [expr {!$var}]
 }

Using the not operator (!) has, apart from being straightforward, the advantage that it also accepts the other allowed forms for truth values (yes, no, on, off, true, false). Also, as every non-zero int or double implies 'true' for expr, the other alternatives may lead to subtle bugs.

escargo has this alternative:

 proc toggle varName {
     upvar 1 $varName var
     set var [expr {1 - $var}]
 }

''This is a clearly inferior alternative (probably on the basis of performance, but also because of the subtle bugs), but I wanted to include it for completeness. In fact, I found a bug in a Fortran compiler once where code optimization turned the expression

    TOGGLE = 1 - TOGGLE

into a decrement instruction. That made my Fortran program misbehave in mysterious ways until I figured out what was going wrong.''


KPV not quite the same thing, but I've liked the following idiom for normalizing boolean values, i.e. converting all true values into 1, and all false values into 0:

 set b [expr {!!$b}]

Category Example