Numeric Comparisons 101 - if

Numeric Comparisons 101 - if

Like most languages, Tcl supports an if command. The syntax is:

  • if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?

The words then and else are optional, although generally then is left out and else is used.

The test expression following if should return a value that can be interpreted as representing "true" or "false":

False True
a numeric value 0 all others
yes/no no yes
true/false false true

If the test expression returns a string "yes"/"no" or "true"/"false", the case of the return is not checked. True/FALSE or YeS/nO are legitimate returns.

If the test expression evaluates to True, then body1 will be executed.

If the test expression evaluates to False, then the word after body1 will be examined. If the next word is elseif, then the next test expression will be tested as a condition. If the next word is else then the final body will be evaluated as a command.

The test expression following the word if is evaluated in the same manner as in the expr command.

The test expression following if may be enclosed within quotes, or braces. If it is enclosed within braces, it will be evaluated within the if command, and if enclosed within quotes it will be evaluated during the substitution phase, and then another round of substitutions will be done within the if command.

Note: This extra round can cause unexpected trouble - avoid it.


Example

set x 1

if {$x == 2} {puts "$x is 2"} else {puts "$x is not 2"}

if {$x != 1} {
    puts "$x is != 1"
} else {
    puts "$x is 1"
}

if $x==1 {puts "GOT 1"}

#
# Be careful, this is just an example
# Usually you should avoid such constructs,
# it is less than clear what is going on and it can be dangerous
#
set y x
if "$$y != 1" {
    puts "$$y is != 1"
} else {
    puts "$$y is 1"
}

#
# A dangerous example: due to the extra round of substitution,
# the script stops
#
set y {[exit]}
if "$$y != 1" {
    puts "$$y is != 1"
} else {
    puts "$$y is 1"
}