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 编程语言中可用的所有赋值运算符:

  1. #import <Foundation/Foundation.h>
  2. int main() {
  3. int a = 21;
  4. int c ;
  5. c = a;
  6. NSLog(@"Line 1 - = Operator Example, Value of c = %d\n", c );
  7. c += a;
  8. NSLog(@"Line 2 - += Operator Example, Value of c = %d\n", c );
  9. c -= a;
  10. NSLog(@"Line 3 - -= Operator Example, Value of c = %d\n", c );
  11. c *= a;
  12. NSLog(@"Line 4 - *= Operator Example, Value of c = %d\n", c );
  13. c /= a;
  14. NSLog(@"Line 5 - /= Operator Example, Value of c = %d\n", c );
  15. c = 200;
  16. c %= a;
  17. NSLog(@"Line 6 - %= Operator Example, Value of c = %d\n", c );
  18. c <<= 2;
  19. NSLog(@"Line 7 - <<= Operator Example, Value of c = %d\n", c );
  20. c >>= 2;
  21. NSLog(@"Line 8 - >>= Operator Example, Value of c = %d\n", c );
  22. c &amp;= 2;
  23. NSLog(@"Line 9 - &amp;= Operator Example, Value of c = %d\n", c );
  24. c ^= 2;
  25. NSLog(@"Line 10 - ^= Operator Example, Value of c = %d\n", c );
  26. c |= 2;
  27. NSLog(@"Line 11 - |= Operator Example, Value of c = %d\n", c );
  28. }

结果如下:

  1. 2022-07-07 22:00:19.263 demo[21858] Line 1 - = Operator Example, Value of c = 21
  2. 2022-07-07 22:00:19.263 demo[21858] Line 2 - += Operator Example, Value of c = 42
  3. 2022-07-07 22:00:19.263 demo[21858] Line 3 - -= Operator Example, Value of c = 21
  4. 2022-07-07 22:00:19.263 demo[21858] Line 4 - *= Operator Example, Value of c = 441
  5. 2022-07-07 22:00:19.263 demo[21858] Line 5 - /= Operator Example, Value of c = 21
  6. 2022-07-07 22:00:19.264 demo[21858] Line 6 - %= Operator Example, Value of c = 11
  7. 2022-07-07 22:00:19.264 demo[21858] Line 7 - <<= Operator Example, Value of c = 44
  8. 2022-07-07 22:00:19.264 demo[21858] Line 8 - >>= Operator Example, Value of c = 11
  9. 2022-07-07 22:00:19.264 demo[21858] Line 9 - &= Operator Example, Value of c = 2
  10. 2022-07-07 22:00:19.264 demo[21858] Line 10 - ^= Operator Example, Value of c = 0
  11. 2022-07-07 22:00:19.264 demo[21858] Line 11 - |= Operator Example, Value of c = 2

分类导航