Stay weird. Stay different.

0%

关于const,static,extern

一直对于这几个属性掌握的不是很好,也算是上学时候不好好学校的后遗症,今天抓紧时间总结下。

  1. const与宏的区别
  2. const的作用
  3. const使用场景
  4. static与extern的使用
  5. static与const的使用
  6. extern与const的使用

const与宏的区别

const最大的区别在于,宏是不做类型检查的。苹果官方也推荐使用const,但可以定义一些函数,const不能。

const的作用

const修饰的变量是只读的,这就牵扯到了指向const的指针const指针的蛋疼概念

1
2
3
4
const int* p1; 
int const* p2; //这两个都是指向const的指针,即指针指向的内容不能修改 *p1 = 12是错误的

int* const p3=&a; //const指针,即指针的值不能概念,也就是指针指向的内存地址不能修改 p1 = &b是错误的

const使用场景

其实简单一句话,任何只读的变量都用const修饰

static与extern的使用

static的作用:

  • 修饰局部变量
    1. 延长局部变量的生命周期。
    2. 局部变量只在内存中生成一份。
    3. 修改局部变量的作用域。
  • 修饰全局变量
    1. 只能在本文件中访问,修改全局变量作用域,生命周期不改变
    2. 避免重复定义全局变量

extern的作用:

  • 只是获取全局变量的值,不能用于定义变量
  • 现在当前文件查找全局变量,如果没有再去其他文件查找

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    #include <stdio.h>

    //static修饰全局变量,修改了作用域,生命周期不变,是为了避免重复定义全局变量
    static int age = 20;

    void test(){
    //static修饰局部变量,修改了作用域,延长了生命周期,并确保了age只在内存保持一份
    static int age = 0;
    age++;
    printf("test local age = %d\n", age);
    printf("%p\n",&age);
    }

    int main(int argc, char *argv[]) {
    test();
    test();

    printf("main global age = %d\n",age);
    printf("%p\n",&age);

    //获取全局变量的值
    extern int age;
    printf("global age = %d\n",age);
    printf("%p\n",&age);

    age ++;
    printf("global age = %d\n",age);
    printf("%p\n",&age);
    return 0;
    }

    //输出结果

    /*
    test local age = 1
    0x10d11701c
    test local age = 2
    0x10d11701c
    main global age = 20
    0x10d117018
    global age = 20
    0x10d117018
    global age = 21
    0x10d117018
    */

static与const的使用

  • staticconst作用:声明一个只读的静态变量
  • 开发使用场景:在一个文件中经常使用的字符串常量,可以使用staticconst组合生成静态的全局只读常量
  • IOS中经常使用staticconst来代替

    1
    static  NSString * const key = @"name";

extern与const的使用

  • 开发使用场景:在多个文件中经常使用的字符串常量,可以使用externconst组合生成静态的全局只读常量

    1
    2
    //.h
    extern NSString *const EOCStringConstant;
    1
    2
    //.m
    NSString *const EOCStringConstant = @"xxx";

参考:
【如何正确使用const,static,extern】|那些人追的干货