Objective-C 中的賦值運算子



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
|= 按位或和賦值運算子 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 );

}

編譯並執行上述程式時,會產生以下結果:

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