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
上一篇:
Objective-C運算符
下一篇:
Objective-C迴圈