C語言賦值運算符
賦值運算符
還有C語言支持以下賦值運算符:
運算符 | 描述 | 示例 |
---|---|---|
= | 簡單的賦值操作符,分配值從右邊的操作數到左側的操作數 | C = A + B 將分配值 A + B 到 C |
+= | ADD與賦值運算符,它增加右操作數左操作數並分配結果左操作數 | C += A 相當於 C = C + A |
-= | 減法與賦值運算符,它從左側的操作數減去右操作數和分配結果到左操作數 | C -= A 相當於 C = C - A |
*= | 乘法與賦值運算符,它乘以右邊的操作數與左操作數和分配結果左操作數 | C *= A 相當於 C = C * A |
/= | 除法與賦值運算符,它把左操作數與右操作數和分配結果左操作數 | C /= A 相當於 C = C / A |
%= | 模量和賦值運算符,它需要使用兩個操作數的模量和分配結果左操作數 | C %= A 相當於 C = C % A |
<<= | 左移位並賦值運算符 | C <<= 2 和 C = C << 2 一樣 |
>>= | 向右移位並賦值運算符 | C >>= 2 和 C = C >> 2 一樣 |
&= | 按位與賦值運算符 | C &= 2 和 C = C & 2 一樣 |
^= | 按位異或並賦值運算符 | C ^= 2 和 C = C ^ 2 一樣 |
|= | 按位或並賦值運算符 | C |= 2 和 C = C | 2 一樣 |
例子
試試下麵的例子就明白了可用C語言編程的所有賦值運算符:
#include <stdio.h> main() { int a = 21; int c ; c = a; printf("Line 1 - = Operator Example, Value of c = %d ", c ); c += a; printf("Line 2 - += Operator Example, Value of c = %d ", c ); c -= a; printf("Line 3 - -= Operator Example, Value of c = %d ", c ); c *= a; printf("Line 4 - *= Operator Example, Value of c = %d ", c ); c /= a; printf("Line 5 - /= Operator Example, Value of c = %d ", c ); c = 200; c %= a; printf("Line 6 - %= Operator Example, Value of c = %d ", c ); c <<= 2; printf("Line 7 - <<= Operator Example, Value of c = %d ", c ); c >>= 2; printf("Line 8 - >>= Operator Example, Value of c = %d ", c ); c &= 2; printf("Line 9 - &= Operator Example, Value of c = %d ", c ); c ^= 2; printf("Line 10 - ^= Operator Example, Value of c = %d ", c ); c |= 2; printf("Line 11 - |= Operator Example, Value of c = %d ", c ); }
當編譯和執行上麵的程序就產生以下結果:
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