- Objective-C 基础
- Objective-C - 首页
- Objective-C - 概述
- Objective-C - 环境设置
- Objective-C - 程序结构
- Objective-C - 基本语法
- Objective-C - 数据类型
- Objective-C - 变量
- Objective-C - 常量
- Objective-C - 运算符
- Objective-C - 循环
- Objective-C - 决策
- Objective-C - 函数
- Objective-C - 块 (Blocks)
- Objective-C - 数字
- Objective-C - 数组
- Objective-C - 指针
- Objective-C - 字符串
- Objective-C - 结构体
- Objective-C - 预处理器
- Objective-C - typedef
- Objective-C - 类型转换
- Objective-C - 日志处理
- Objective-C - 错误处理
- 命令行参数
- 高级 Objective-C
- Objective-C - 类与对象
- Objective-C - 继承
- Objective-C - 多态
- Objective-C - 数据封装
- Objective-C - 分类 (Categories)
- Objective-C - 伪装 (Posing)
- Objective-C - 扩展 (Extensions)
- Objective-C - 协议 (Protocols)
- Objective-C - 动态绑定
- Objective-C - 复合对象
- Obj-C - Foundation 框架
- Objective-C - 快速枚举
- Obj-C - 内存管理
- Objective-C 有用资源
- Objective-C - 快速指南
- Objective-C - 有用资源
- Objective-C - 讨论
Objective-C 中的 sizeof 运算符和三元运算符
Objective-C 语言还支持一些其他重要的运算符,包括sizeof 和?:。
| 运算符 | 描述 | 示例 |
|---|---|---|
| sizeof() | 返回变量的大小。 | 如果 a 是整数,sizeof(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
objective_c_operators.htm
广告