zoukankan      html  css  js  c++  java
  • Static和Extern关键字理解

    1.当static关键字修饰局部变量时,只会初始化一次且在程序中只有一份内存;

    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.view.backgroundColor = [UIColor whiteColor];
        [self test];
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        
        NSLog(@"---------- viewWillAppear -------------");
        [self test];
    }
    
    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
        
        NSLog(@"---------- viewDidAppear -------------");
        [self test];
    }
    
    - (void)test {
        NSString *normalString;
        static NSString *staticString;
        
        NSLog(@"normal = %p, static = %p", &normalString, &staticString);
    }
    
    @end

         总计:3个输出的内存空间为同一个

    2.关键字static不可以改变局部变量的作用域,但可延长局部变量的生命周期(直到程序结束才销毁)。

    static NSInteger age;

    3.static关键字修饰全局变量:

        当static关键字修饰全局变量时,作用域仅限于当前文件,外部类是不可以访问到该全局变量的(即使在外部使用extern关键字也无法访问)。

    4.extern关键字:

        想要访问全局变量可以使用extern关键字(全局变量定义不能有static修饰)。

    by:liming

  • 相关阅读:
    java之JDBC
    git删除未监视的文件
    java之正则表达式
    linux命令之信息显示与搜索文件命令
    linux命令之文件备份与压缩命令
    gitlab中修改项目名称客户端修改方法
    linux中使用unzip命令中文乱码解决办法
    使用Python进行统计量描述
    Machine Learning
    Courase Neural Networks for Machine Learning Lecture1 Note
  • 原文地址:https://www.cnblogs.com/widgetbox/p/12608951.html
Copyright © 2011-2022 走看看