Version 5 of Toggling a Boolean Variable

Updated 2002-11-06 16:36:16

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, but I wanted to include it for completeness.


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