Tcl Tutorial Lesson 7

Difference between version 11 and 12 - Previous - Next

**Numeric Comparisons 101 - if**


!!!!!!
'''[Tcl Tutorial Lesson 6a%|%Previous lesson%|%]''' | '''[Tcl Tutorial Index%|%Index%|%]''' | '''[Tcl Tutorial Lesson 8%|%Next lesson%|%]'''
!!!!!!

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 usually `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` should be enclosed within braces.  This causes the expression to be evaluated within the `if` command.

''Note:'' as was explained in the [Tcl Tutorial Lesson 6%|%discussion of the expr command%|%], you should always use braces around expressions.

----

***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"
}
======

<<discussion>> Resulting output
======none
1 is not 2
1 is 1
======
<<enddiscussion>>

!!!!!!
'''[Tcl Tutorial Lesson 6a%|%Previous lesson%|%]''' | '''[Tcl Tutorial Index%|%Index%|%]''' | '''[Tcl Tutorial Lesson 8%|%Next lesson%|%]'''
!!!!!!