D Programming - Operators Precedence


Advertisements

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators are given precedence over others.

For example, the multiplication operator has higher precedence than the addition operator.

Let us consider an expression

x = 7 + 3 * 2.

Here, x is assigned 13, not 20. The simple reason is, the operator * has higher precedence than +, hence 3*2 is calculated first and then the result is added into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators are evaluated first.

Category Operator Associativity
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

Example

Try the following example to understand the operator precedence available in D programming language −

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;
}

When you compile and execute the above program, it produces the following result −

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
Advertisements