# Tcl if...else語句

if語句可以跟着一個可選的else語句，else語句塊執行時，布爾表達式是假的。

## 語法

if {boolean_expression} { # statement(s) will execute if the boolean expression is true } else { # statement(s) will execute if the boolean expression is false }

TCL語言使用expr內部命令，因此它不是明確地使用expr語句所需的。

## 示例

#!/usr/bin/tclsh set a 100 #check the boolean condition if {\$a < 20 } { #if condition is true then print the following puts "a is less than 20" } else { #if condition is false then print the following puts "a is not less than 20" } puts "value of a is : \$a"

a is not less than 20; value of a is : 100

## if...else if...else 語句

if語句可以跟着一個可選的else if ... else語句，使用單個if 測試各種條件if...else if 聲明是非常有用的。

• 一個if可以有零或一個else，它必須跟在else if之後。

• 一個if語句可以有零到多個else if，並且它們必須在else之前。

• 一旦一個 else if 成功，任何剩餘else if 或else 不會再被測試。

### 語法

Tcl語言的 if...else if...else語句的語法是：

if {boolean_expression 1} { # Executes when the boolean expression 1 is true } elseif {boolean_expression 2} { # Executes when the boolean expression 2 is true } elseif {boolean_expression 3} { # Executes when the boolean expression 3 is true } else { # executes when the none of the above condition is true }

### 示例

#!/usr/bin/tclsh set a 100 #check the boolean condition if { \$a == 10 } { # if condition is true then print the following puts "Value of a is 10" } elseif { \$a == 20 } { # if else if condition is true puts "Value of a is 20" } elseif { \$a == 30 } { # if else if condition is true puts "Value of a is 30" } else { # if none of the conditions is true puts "None of the values is matching" } puts "Exact value of a is: \$a"

None of the values is matching
Exact value of a is: 100