Objective-C sizeof 和三元运算符

Objective-C 支持的其他少量重要运算符,包括 sizeof? ::

运算符描述实例
sizeof()返回变量的大小。sizeof(a), 其中 a 是整数,将返回 4。
&返回变量的地址。&a; 将给出变量的实际地址。
*指向变量的指针。*a; 将指针指向变量。
? :条件表达式如果条件为 true ? X : 否则 Y

实例

尝试以下实例以了解 Objective-C 编程语言中可用的所有其他运算符:

  1. #import <Foundation/Foundation.h>
  2. int main() {
  3. int a = 4;
  4. short b;
  5. double c;
  6. int* ptr;
  7. /* example of sizeof operator */
  8. NSLog(@"Line 1 - Size of variable a = %d\n", sizeof(a) );
  9. NSLog(@"Line 2 - Size of variable b = %d\n", sizeof(b) );
  10. NSLog(@"Line 3 - Size of variable c= %d\n", sizeof(c) );
  11. /* example of &amp; and * operators */
  12. ptr = &a;/* 'ptr' now contains the address of 'a'*/
  13. NSLog(@"value of a is %d\n", a);
  14. NSLog(@"*ptr is %d.\n", *ptr);
  15. /* example of ternary operator */
  16. a = 10;
  17. b = (a == 1) ? 20: 30;
  18. NSLog(@"Value of b is %d\n", b );
  19. b = (a == 10) ? 20: 30;
  20. NSLog(@"Value of b is %d\n", b );
  21. }

结果如下:

  1. 2022-07-07 22:46:22.702 demo[24593] Line 1 - Size of variable a = 4
  2. 2022-07-07 22:46:22.703 demo[24593] Line 2 - Size of variable b = 2
  3. 2022-07-07 22:46:22.703 demo[24593] Line 3 - Size of variable c= 8
  4. 2022-07-07 22:46:22.703 demo[24593] value of a is 4
  5. 2022-07-07 22:46:22.703 demo[24593] *ptr is 4.
  6. 2022-07-07 22:46:22.703 demo[24593] Value of b is 30
  7. 2022-07-07 22:46:22.703 demo[24593] Value of b is 20

分类导航