Version 10 of Boolean

Updated 2011-05-03 01:44:26 by MG

True or False. Tcl has no separate Boolean type, like in C, the integers 0 (false) and 1 (true - in fact any nonzero integer) are used.

NEM: Although expr will also accept "true" and "false" (and "yes"/"no"..) as Boolean values.

1S In fact, there's no separate Integer type in Tcl as well -- everything is a string. A proper boolean value is either a proper integer, with, like in C, zero meaning false and non-zero meaning true, or one of the following: yes, no, true, false, on, or off.

RS The canonical forms however, like expr produces them, are 1 and 0.

See Boolean Logic or Integers as Boolean Functions.


  Boolean and the comparision operators '''==''' and '''!='''

HaO 2011-05-02 Comparisions with == or != do not work with booleans not in canonical form:

% expr {true == 1}
0

This issue may be avoided using the bool() function to bring strings in boolean canonical form:

% expr {bool(true) == bool(1)}
1

This is only recommeded if two variables contain boolean data.

expr {bool($b1) == bool($b2)}

otherwise, one would use:

expr { $b1 }
expr { ! $b1 }


MG The string is command also recognises booleans:

proc trueorfalse {str} {
  if { ![string is boolean -strict $str] } {
       return -1; # not a boolean
     }
  return [string is true $str]
}
% trueorfalse foo
-1
% trueorfalse yes
1
% trueorfalse off
0