赋值运算符
还有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