第9课 - const 和 volatile 分析

const只读变量

  ·const修饰的变量是只读的,本质海是变量;

  ·const修饰的局部变量在栈上分配空间;

  ·const修饰的全局变量在全局数据区分配空间;

  ·const只在编译期有用,在运行期无用。

const修饰的变量不是真的常量,它只是告诉编译器该变量不能出现在赋值符号的左边。

const全局变量的分歧

  在现代的C语言编译器中,修改const全局变量将导致程序崩溃;

  标准C语言编译器不会将const修饰的全局变量存储于只读存储器中,而是存储于可修改的全局数据区,其值依然可以改变。

 #include<stdio.h>
 const int g_cc = 2;
 
 int main()
 {
    const int cc = 1;
    int* p = (int*)&cc;
    printf("cc = %d\n",cc);
    *p = 3;
    printf("cc = %d\n",cc);
    
    p = (int*)&g_cc;
    
    printf("g_cc = %d\n",g_cc);
    
    *p = 4;
    printf("g_cc = %d\n",g_cc);
    
    return 0;
 }
扫描二维码关注公众号,回复: 7847652 查看本文章

const的本质

  ·C语言中的const使得变量具有只读属性;

  ·现代C编译器中的const将具有全局生命周期的变量存储于只读存储区;

  ·const不能定义真正意义上的常量。

#include <stdio.h>

const int g_array[5] = {0};

void modify(int* p, int v)
{
    *p = v;
}

int main()
{
    int const i = 0;
    const static int j = 0;
    int const array[5] = {0};
    
    modify((int*)&i, 1);           // ok
    modify((int*)&j, 2);           // error
    modify((int*)&array[0], 3);    // ok
    modify((int*)&g_array[0], 4);  // error
    
    printf("i = %d\n", i);
    printf("j = %d\n", j);
    printf("array[0] = %d\n", array[0]);
    printf("g_array[0] = %d\n", g_array[0]);
    
    return 0;
}

const修饰参数和返回值

  ·const修饰函数参数表示在函数体内不希望改变函数参数的值;

  ·const修饰函数返回值表示返回值不可改变,多用于返回指针的情形;

C语言中的字符串字面量存储于只读存储区中,在程序中需要使用const char*指针。

#include <stdio.h>

const char* f(const int i)
{
    i = 5;
    
    return "Delphi Tang";  //字符串字面量
}

int main()
{
    char* pc = f(0);
    
    printf("%s\n", pc);
    
    pc[6] = '_';
    
    printf("%s\n", pc);
    
    return 0;
}

深藏不露的volatile

  ·volatile可理解为“编译器警告指示字”;

  ·volatile告诉编译器必须每次去内存中取变量值;

  ·volatile主要修饰可能被多个线程访问的变量;

  ·volatile也可以修饰可能被未知因素更改的变量。

猜你喜欢

转载自www.cnblogs.com/kojull/p/11854384.html