TCL運算符優先級

運算符優先級決定術語的表達分組。這會影響一個表達式是如何進行計算。某些運算符的優先級高於其他運算符;例如,乘法運算符的優先級比所述加法運算高。

例如x= 7+ 3 *2;這裏,x被賦值13,而不是20,因爲運算符 * 優先級高於+,所以它首先被乘以 3 * 2,然後加上7。

這裏,具有最高優先級的操作出現在表格上方,那些具有最低出現在底部。在一個表達式,更高的優先級運算符將首先計算。

分類

操作符

關聯

Unary

+ -

Right to left

Multiplicative

* / %

Left to right

Additive

+ -

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

^

Left to right

Bitwise OR

|

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Ternary

?:

Right to left

示例

試試下面的例子來理解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