您的位置:首页 > 其它

[const与宏]-区别和使用

2016-08-09 00:00 92 查看
摘要: 1:const 和 宏的区别?
2:const的使用?
3:const的使用场景?

01-我们一般把常用的字符串、基本变量定义成宏

02-苹果一直推荐我们使用const、而不是宏

03-而且在swift中,苹果已经取缔了使用宏,不能再使用了

1:宏 与 const 的区别?

编译时刻 - 宏:在预编译时刻 const:在编译时刻

编译检查 - 宏不会编译检查 const:有编译检查

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

宏的坏处:大量使用宏,会导致预编译的时间过长

误解:有一些博客说:大量使用宏,让使内存暴增?

解释:其实这是错误的说法,大量使用宏,其实并不会使内存暴增,因为你大量使用的这个宏都是同一个地址,它只会让你的预编译时间增大而已,让内存暴增是错误的说法

// const有编译检查

#define XJAppName @"魔多" 123  编译不会检查
CGFloat const a = 3; 123   编译检查会显示错误

// 宏可以定义方法或者函数

#define XJUserDefaultKey [NSUserDefaults standardUserDefaults]
const XJUserDefaultKey1 = [NSUserDefaults standardUserDefaults];

[XJUserDefaultKey setObject:@"123" forKey:@"name"];
[XJUserDefaultKey objectForKey:@"name"];


2:const的基本使用?

const的作用:修饰右边的基本变量或者指针变量,如int a; int *p;

const修饰的变量只能读,不能修改

// 面试题:
int * const p1;  // p1:只读    *p1:可修改(变量)
int const * p2;  // p2:可修改(变量)  *p2:只读
const int * p3;  // p3:可修改(变量)  *p3:只读
const int * const p4;  // p4:只读   *p4:只读
int const * const p5;  // p5:只读   *p5:只读

// 正确
int a = 3;
a = 5;

// 错误(只读){这两种写法一样}
//int const b = 3;
const int b = 3;
//b = 5;

// 修饰指针变量
/*
int c = 3;
int *p = &c;
// 修改c的值(地址修改)
c = 5;
*p = 8;
*/

/*
int c = 3;
int const *p = &c;
// 修改c的值(地址修改)
c = 5;
*p = 8;
*/


3:const的使用场景?

修饰全局变量 => 全局只读变量

修饰方法中参数

如:修饰全局变量

#import "ViewController.h"

//#define XJNameKey @"123"
// const修饰右边的XJNameKey不能修改,只读
NSString * const XJNameKey = @"123";

@interface ViewController ()

@end

/**
const的使用场景
*  1: 修饰全局变量 => 全局只读变量
*  2: 修饰方法中参数
*/

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
[[NSUserDefaults standardUserDefaults] setObject:@"123" forKey:XJNameKey];
//XJNameKey = @"321";  // 错误,const修饰了不能修改了,

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
[[NSUserDefaults standardUserDefaults] objectForKey:XJNameKey];
}


如:修饰方法中参数:

- (void)viewDidLoad {
[super viewDidLoad];
[[NSUserDefaults standardUserDefaults] setObject:@"123" forKey:XJNameKey];
//XJNameKey = @"321";  // 错误,const修饰了不能修改了,

int a = 0;
[self test:&a];

}

- (void)test:(int const *)a {
*a = 3; // 错误不能修改
}

- (void)test:(int *)a {
*a = 3; // 可以能修改
}


意见反馈邮件:1415429879@qq.com
欢迎你们的阅读和赞赏、谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  const 宏定义