Tcl - 運算子優先順序



運算子優先順序決定了表示式中各項的組合方式。這影響了表示式的計算方式。某些運算子比其他運算子具有更高的優先順序;例如,乘法運算子的優先順序高於加法運算子。

例如:x = 7 + 3 * 2; 這裡,x 被賦值為 13,而不是 20,因為運算子 * 的優先順序高於 +,所以它首先計算 3 * 2,然後加到 7 中。

這裡,優先順序最高的運算子出現在表格的頂部,優先順序最低的出現在底部。在一個表示式中,優先順序較高的運算子將首先被計算。

類別 運算子 結合性
一元 + - 從右到左
乘法 * / % 從左到右
加法 + - 從左到右
移位 << >> 從左到右
關係 < <= > >= 從左到右
相等 == != 從左到右
按位與 & 從左到右
按位異或 ^ 從左到右
按位或 | 從左到右
邏輯與 && 從左到右
邏輯或 || 從左到右
三元 ?: 從右到左

示例

嘗試以下示例以瞭解 Tcl 語言中可用的運算子優先順序:

#!/usr/bin/tclsh

set a 20
set b 10
set c 15
set d 5

set  e [expr [expr $a + $b] * $c / $d ]     ;# ( 30 * 15 ) / 5
puts "Value of (a + b) * c / d is : $e\n"

set  e [expr  [expr [expr $a + $b] * $c] / $d]   ;#  (30 * 15 ) / 5]
puts "Value of ((a + b) * c) / d is  : $e\n"

set  e  [expr [expr $a + $b] * [expr $c / $d] ]   ;# (30) * (15/5)
puts "Value of (a + b) * (c / d) is  : $e\n"

set  e  [expr $a + [expr $b * $c ] / $d ] ;#  20 + (150/5)
puts "Value of a + (b * c) / d is  :  $e\n" 

編譯並執行上述程式時,將產生以下結果:

Value of (a + b) * c / d is : 90

Value of ((a + b) * c) / d is  : 90

Value of (a + b) * (c / d) is  : 90

Value of a + (b * c) / d is  :  50
tcl_operators.htm
廣告
© . All rights reserved.