[const與宏]-區別和使用

01-咱們通常把經常使用的字符串、基本變量定義成宏面試

02-蘋果一直推薦咱們使用const、而不是宏swift

03-並且在swift中,蘋果已經取締了使用宏,不能再使用了函數

1:宏 與 const 的區別?spa

  1. 編譯時刻 - 宏:在預編譯時刻     const:在編譯時刻
  2. 編譯檢查 - 宏不會編譯檢查       const:有編譯檢查
  3. 宏的好處:宏能夠定義函數、方法等等     const:不能夠
  4. 宏的壞處:大量使用宏,會致使預編譯的時間過長

誤解:有一些博客說:大量使用宏,讓使內存暴增?指針

解釋:其實這是錯誤的說法,大量使用宏,其實並不會使內存暴增,由於你大量使用的這個宏都是同一個地址,它只會讓你的預編譯時間增大而已,讓內存暴增是錯誤的說法code

// 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的基本使用?博客

  1. const的做用:修飾右邊的基本變量或者指針變量,如int a;  int *p;
  2. 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的使用場景?it

  1. 修飾全局變量  => 全局只讀變量
  2. 修飾方法中參數

如:修飾全局變量

#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 歡迎大家的閱讀和讚揚、謝謝!

相關文章
相關標籤/搜索