Objective-C 中的 sizeof 和三元运算符
还有一些其他重要的运算符,包括 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 ); }
当你编译并执行上面的程序时,它会产生以下结果 −
2013-09-07 22:46:22.702 demo[24593] Line 1 - Size of variable a = 4 2013-09-07 22:46:22.703 demo[24593] Line 2 - Size of variable b = 2 2013-09-07 22:46:22.703 demo[24593] Line 3 - Size of variable c= 8 2013-09-07 22:46:22.703 demo[24593] value of a is 4 2013-09-07 22:46:22.703 demo[24593] *ptr is 4. 2013-09-07 22:46:22.703 demo[24593] Value of b is 30 2013-09-07 22:46:22.703 demo[24593] Value of b is 20