Objective-C中还有其他一些重要的运算符,包括sizeof
和?:
三元运算符,Objective-C语言也都支持。
运算符 | 描述 | 示例 |
---|---|---|
sizeof() |
返回变量的大小 | sizeof(a) , 这里如果变量a 是整数,则将返回:4 。 |
& |
返回变量的地址。 | &a 将返回变量的实际地址。 |
* |
指向变量的指针。 | *a 将指向变量。 |
? : |
条件表达式 | 如果条件为真?然后是X 值:否则为Y 值 |
例子
尝试以下示例来了解Objective-C编程语言中可用的所有其他运算符 -
#import <Foundation/Foundation.h>
int main() {
int a = 4;
short b;
double c;
int* ptr;
/* example of sizeof operator */
NSLog(@"Line 1 - Size of variable a = %d\n", sizeof(a) );
NSLog(@"Line 2 - Size of variable b = %d\n", sizeof(b) );
NSLog(@"Line 3 - Size of variable c= %d\n", sizeof(c) );
/* example of & and * operators */
ptr = &a; /* 'ptr' now contains the address of 'a'*/
NSLog(@"value of a is %d\n", a);
NSLog(@"*ptr is %d.\n", *ptr);
/* example of ternary operator */
a = 10;
b = (a == 1) ? 20: 30;
NSLog(@"Value of b is %d\n", b );
b = (a == 10) ? 20: 30;
NSLog(@"Value of b is %d\n", b );
}
执行上面示例代码,得到以下结果:
2018-11-14 05:18:49.270 main[174436] Line 1 - Size of variable a = 4
2018-11-14 05:18:49.271 main[174436] Line 2 - Size of variable b = 2
2018-11-14 05:18:49.271 main[174436] Line 3 - Size of variable c= 8
2018-11-14 05:18:49.271 main[174436] value of a is 4
2018-11-14 05:18:49.271 main[174436] *ptr is 4.
2018-11-14 05:18:49.272 main[174436] Value of b is 30
2018-11-14 05:18:49.272 main[174436] Value of b is 20