D語言賦值運算子


下列是D語言支援賦值操作符:

運算子 描述 範例
= 簡單賦值運算子,分配從右側運算元的值,以左側運算元 C = A + B will assign value of A + B into C
+= 新增和賦值操作符,它增加了右運算元為左運算元和結果分配給左運算元 C += A is equivalent to C = C + A
-= 減和賦值操作符,它減去右邊的運算元從左邊的運算元,並將結果賦值給左運算元 C -= A is equivalent to C = C - A
*= 乘法和賦值操作符,它乘以右邊的運算元與左運算元和結果分配給左運算元 C *= A is equivalent to C = C * A
/= 除法和賦值操作符,它分為左運算元與右邊的運算元,並將結果賦值給左運算元 C /= A is equivalent to C = C / A
%= 模量和賦值操作符,它採用模使用兩個運算元和結果分配給左運算元 C %= A is equivalent to C = C % A
<<= 左移位並賦值運算子 C <<= 2 is same as C = C << 2
>>= 向右移位並賦值運算子 C >>= 2 is same as C = C >> 2
&= 按位元AND賦值運算子 C &= 2 is same as C = C & 2
^= 按位元互斥或和賦值運算子 C ^= 2 is same as C = C ^ 2
|= OR運算和賦值運算子 C |= 2 is same as C = C | 2

範例

試試下面的例子就明白了提供D程式設計語言的所有賦值運算子:

import std.stdio;

int main(string[] args)
{
   int a = 21;
   int c ;

   c =  a;
   writefln("Line 1 - =  Operator Example, Value of c = %d
", c );

   c +=  a;
   writefln("Line 2 - += Operator Example, Value of c = %d
", c );

   c -=  a;
   writefln("Line 3 - -= Operator Example, Value of c = %d
", c );

   c *=  a;
   writefln("Line 4 - *= Operator Example, Value of c = %d
", c );

   c /=  a;
   writefln("Line 5 - /= Operator Example, Value of c = %d
", c );

   c  = 200;
   c = c % a;
   writefln("Line 6 - %s= Operator Example, Value of c = %d
",'x25', c );

   c <<=  2;
   writefln("Line 7 - <<= Operator Example, Value of c = %d
", c );

   c >>=  2;
   writefln("Line 8 - >>= Operator Example, Value of c = %d
", c );

   c &=  2;
   writefln("Line 9 - &= Operator Example, Value of c = %d
", c );

   c ^=  2;
   writefln("Line 10 - ^= Operator Example, Value of c = %d
", c );

   c |=  2;
   writefln("Line 11 - |= Operator Example, Value of c = %d
", c );
   return 0;
}

當編譯並執行上面的程式它會產生以下結果:

Line 1 - =  Operator Example, Value of c = 21

Line 2 - += Operator Example, Value of c = 42

Line 3 - -= Operator Example, Value of c = 21

Line 4 - *= Operator Example, Value of c = 441

Line 5 - /= Operator Example, Value of c = 21

Line 6 - %= Operator Example, Value of c = 11

Line 7 - <<= Operator Example, Value of c = 44

Line 8 - >>= Operator Example, Value of c = 11

Line 9 - &= Operator Example, Value of c = 2

Line 10 - ^= Operator Example, Value of c = 0

Line 11 - |= Operator Example, Value of c = 2