D語言運算符優先級
運算符優先級決定的條款在表達式中的分組。這會影響一個表達式如何計算。某些運算符的優先級高於其他;例如,乘法運算符的優先級比加法運算符高。
例如X =7 +3* 2; 這裏,x被賦值13,而不是20,因爲運算符*的優先級高於+,所以它首先被乘以3 * 2,然後再加上7。
這裏,具有最高優先級的操作出現在表的頂部,那些具有最低出現在底部。在表達式中,優先級較高的運算符將首先計算。
分類
Operator
關聯
Postfix
() [] -> . ++ - -
Left to right
Unary
+ - ! ~ ++ - - (type)* & sizeof
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
Conditional
?:
Right to left
Assignment
= += -= *= /= %=>>= <<= &= ^= |=
Right to left
Comma
,
Left to right
例子
試試下面的例子就明白了在D編程語言中的運算符優先級可供選擇:
import std.stdio; int main(string[] args) { int a = 20; int b = 10; int c = 15; int d = 5; int e; e = (a + b) * c / d; // ( 30 * 15 ) / 5 writefln("Value of (a + b) * c / d is : %d
", e ); e = ((a + b) * c) / d; // (30 * 15 ) / 5 writefln("Value of ((a + b) * c) / d is : %d
" , e ); e = (a + b) * (c / d); // (30) * (15/5) writefln("Value of (a + b) * (c / d) is : %d
", e ); e = a + (b * c) / d; // 20 + (150/5) writefln("Value of a + (b * c) / d is : %d
" , e ); return 0; }
當編譯並執行上面的程序它會產生以下結果:
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