Home const与宏的区别
Post
Cancel

const与宏的区别

区别:

处理时刻:宏是预处理时(即在预处理时把宏展开,替换为原来的值),const是编译运行时(编译器在编译时会检查错误,程序在运行时,从内存(堆或栈)中读取)

编译检查:宏不会编译报错,const会包编译错误

宏好处:可以定义函数和方法、const不可以定义函数和方法

宏坏处:大量使用宏,会使编译时间太久,每次编译都需要替换

宏:

1、常见的常量,定义为宏,例如appName,age

1
#define kAge 20

2、常见的方法,定义为宏,例如UserDefault

1
#define kUserDefault [NSUserDefaults standardUserDefaults]

const

const只用于修饰右边的变量(基本数据变量p,指针变量*p),被const修饰的变量是只读的。

1、修饰基本数据变量,这两种方法是一样的,const只修饰右边的变量。

1
2
const int b = 20; // b:只读变量
int const b1 = 20; // b:只读变量

2、修饰指针变量(const修饰右边的变量),所以,它*p1是常量,p1是变量

1
2
const int *p1; // *p1:常量 p1:变量
int const *p1; // *p1:常量 p1:变量

下面这个例子,第一个const,修饰的是*p1,第二个修饰p1,故:*p1、p1都是常量

1
2
3
const int * const p1; // *p1:常量 p1:常量
    
int const * const p1;  // *p1:常量 p1:常量

 3、const 修饰 oc对象

1
2
// 字符串常量
static NSString * const kAppName = @"Wexin";

对于NSString类型的常量,苹果推荐使用const,推荐用法:

1
UIKIT_EXTERN NSString *const UITableViewSelectionDidChangeNotification;
This post is licensed under CC BY 4.0 by the author.

CoreSpotlight应用内搜索

枚举之美(上)