運算子優先順序決定的條款在表示式中的分組。這會影響一個表示式如何計算。某些運算子的優先順序高於其他;例如,乘法運算子的優先順序比加法運算子高。
例如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