D 程式設計 - 運算子優先順序



運算子優先順序決定了表示式中項的組合方式。這會影響表示式的求值方式。某些運算子比其他運算子具有更高的優先順序。

例如,乘法運算子的優先順序高於加法運算子。

讓我們考慮一個表示式

x = 7 + 3 * 2.

這裡,x 被賦值為 13,而不是 20。原因很簡單,* 運算子的優先順序高於 +,因此首先計算 3*2,然後將結果加到 7 中。

這裡,優先順序最高的運算子出現在表的最上方,優先順序最低的運算子出現在表的最下方。在表示式中,優先順序較高的運算子首先計算。

類別 運算子 結合性
字尾 () [] -> . ++ - - 從左到右
一元 + - ! ~ ++ -- (type)* & sizeof 從右到左
乘法 * / % 從左到右
加法 + - 從左到右
移位 << >> 從左到右
關係 < <= > >= 從左到右
相等 == != 從左到右
按位與 & 從左到右
按位異或 ^ 從左到右
按位或 | 從左到右
邏輯與 && 從左到右
邏輯或 || 從左到右
條件 ?: 從右到左
賦值 = += -= *= /= %=>>= <<= &= ^= |= 從右到左
逗號 , 從左到右

示例

嘗試以下示例來了解 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\n",  e ); 
   
   e = ((a + b) * c) / d;    // (30 * 15 ) / 5 
   writefln("Value of ((a + b) * c) / d is  : %d\n" ,  e );  
   
   e = (a + b) * (c / d);   // (30) * (15/5) 
   writefln("Value of (a + b) * (c / d) is  : %d\n",  e );
   
   e = a + (b * c) / d;     //  20 + (150/5) 
   writefln("Value of a + (b * c) / d is  : %d\n" ,  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_programming_operators.htm
廣告
© . All rights reserved.