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

上一篇: D語言sizeof運算符 下一篇: D語言迴圈