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