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

联系我们

邮箱 626512443@qq.com
电话 18611320371(微信)
QQ群 235681453

Copyright © 2015-2024

备案号:京ICP备15003423号-3