运算符优先级决定的条款在表达式中的分组。这会影响一个表达式如何计算。某些运算符的优先级高于其他;例如,乘法运算符的优先级比加法运算符高。
例如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