Objective-C 赋值运算符
Objective-C 语言支持以下赋值运算符:
运算符 | 描述 | 实例 |
---|---|---|
= | 简单赋值运算符,将右侧操作数的值赋给左侧操作数。 | C = A + B 将赋值 A + B 的值给 C |
+= | 加等于运算符,它将右操作数与左操作数相加,并将结果赋给左操作数 | C += A 等于 C = C + A |
-= | 减等于运算符,它从左操作数中减去右操作数,并将结果赋给左操作数 | C -= A 等于 C = C - A |
*= | 乘等于运算符,它将右操作数与左操作数相乘,并将结果赋给左操作数 | C *= A is equivalent to C = C * A |
/= | 除等于运算符,将左操作数与右操作数相除,并将结果赋给左操作数 | C /= A 等于 C = C / A |
%= | 模等于运算符,它使用两个操作数取模,并将结果赋给左操作数 | C %= A 等于 C = C % A |
<<= | 左移位与(AND)赋值运算符 | C <<= 2 与 C = C << 2 一致 |
>>= | 右移位与(AND)赋值运算符 | C >>= 2 与 C = C >> 2 一致 |
&= | 位 AND 赋值运算符 | C &= 2 与 C = C & 2 一致 |
^= | 位异或与赋值运算符 | C ^= 2 与 C = C ^ 2 一致 |
|= | 位包含或与赋值运算符 | 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 );
}
结果如下:
2022-07-07 22:00:19.263 demo[21858] Line 1 - = Operator Example, Value of c = 21
2022-07-07 22:00:19.263 demo[21858] Line 2 - += Operator Example, Value of c = 42
2022-07-07 22:00:19.263 demo[21858] Line 3 - -= Operator Example, Value of c = 21
2022-07-07 22:00:19.263 demo[21858] Line 4 - *= Operator Example, Value of c = 441
2022-07-07 22:00:19.263 demo[21858] Line 5 - /= Operator Example, Value of c = 21
2022-07-07 22:00:19.264 demo[21858] Line 6 - %= Operator Example, Value of c = 11
2022-07-07 22:00:19.264 demo[21858] Line 7 - <<= Operator Example, Value of c = 44
2022-07-07 22:00:19.264 demo[21858] Line 8 - >>= Operator Example, Value of c = 11
2022-07-07 22:00:19.264 demo[21858] Line 9 - &= Operator Example, Value of c = 2
2022-07-07 22:00:19.264 demo[21858] Line 10 - ^= Operator Example, Value of c = 0
2022-07-07 22:00:19.264 demo[21858] Line 11 - |= Operator Example, Value of c = 2