Objective-C賦值運算子

2019-10-16 23:15:44

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