5. 赋值运算符
Objective-C语言支持以下赋值运算符 -
运算符 | 描述 | 示例 |
---|---|---|
= |
简单赋值运算符,将右侧操作数的值分配给左侧操作数 | C = A + B 是将A + B 的值分配给C |
+= |
相加和赋值运算符,它将右操作数添加到左操作数并将结果赋给左操作数 | 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 |
Ι | 按位包含OR和赋值运算符 | C Ι= 2 相当于 C = C Ι 2 |
例子
尝试以下示例来了解Objective-C编程语言中可用的所有赋值运算符 -
#import <Foundation/Foundation.h>
int main() {
int a = 21;
int c ;
c = a;
NSLog(@"Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
NSLog(@"Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
NSLog(@"Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
NSLog(@"Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
NSLog(@"Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
NSLog(@"Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
NSLog(@"Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
NSLog(@"Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
NSLog(@"Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
NSLog(@"Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
NSLog(@"Line 11 - |= Operator Example, Value of c = %d\n", c );
}
执行上面示例代码,得到以下结果:
2018-11-14 05:14:03.383 main[149970] Line 1 - = Operator Example, Value of c = 21
2018-11-14 05:14:03.385 main[149970] Line 2 - += Operator Example, Value of c = 42
2018-11-14 05:14:03.385 main[149970] Line 3 - -= Operator Example, Value of c = 21
2018-11-14 05:14:03.385 main[149970] Line 4 - *= Operator Example, Value of c = 441
2018-11-14 05:14:03.385 main[149970] Line 5 - /= Operator Example, Value of c = 21
2018-11-14 05:14:03.385 main[149970] Line 6 - %= Operator Example, Value of c = 11
2018-11-14 05:14:03.385 main[149970] Line 7 - <<= Operator Example, Value of c = 44
2018-11-14 05:14:03.385 main[149970] Line 8 - >>= Operator Example, Value of c = 11
2018-11-14 05:14:03.385 main[149970] Line 9 - &= Operator Example, Value of c = 2
2018-11-14 05:14:03.385 main[149970] Line 10 - ^= Operator Example, Value of c = 0
2018-11-14 05:14:03.385 main[149970] Line 11 - |= Operator Example, Value of c = 2