Tcl 运算符优先级
运算符优先级决定了表达式中项的分组情况。这影响了表达式的计算顺序。某些运算符的优先级比其他运算符高;例如,乘法运算符的优先级高于加法运算符。
例如: x = 7 + 3 * 2
; 这里,x被赋值为13,而不是20,因为运算符*
的优先级高于+,所以它首先与3 * 2
相乘,然后再加到7上。
在表中,具有最高优先级的运算符出现在顶部,优先级最低的运算符出现在底部。在一个表达式中,高优先级的运算符将首先被计算。
Category | Operator | Associativity |
---|---|---|
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 [expra + 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 [expra + [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