static和extern的使用

2016-06-16  本文已影响24人  952625a28d0d
#import "ViewController.h"

@interface ViewController ()

@end

/*
    static作用:
    1.修饰局部变量
        * 延长这个局部变量的生命周期,只要程序运行,局部变量就会一直存在
        * 局部变量只会分配一次内存,为什么?用static修饰的代码,只会在程序一启动就会执行,以后就不会在执行
 
    2.修饰全局变量
        * 只会修改全局变量的作用域,表示只能是当前文件内使用
 
    extern作用:
    1.声明一个变量,不能定义变量
 
    注意:extern修饰的变量不能初始化
 
    使用场景,一般用于声明全局变量
 */

// 定义静态全局变量
static int i = 2;

int a = 3;

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    // static:修饰的变量,程序一运行就会分配一次内存
   static int i = 0;
    i++;
    NSLog(@"%d",i);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    extern int a;
    
    NSLog(@"%d",a);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end```
上一篇下一篇

猜你喜欢

热点阅读