【C】9.const和volatile分析

const 关键字

  • const修饰的变量是只读的,本质还是变量
  • const修饰的局部变量在栈上分配空间
  • const修饰的全局变量在全局数据区分配空间
  • const只在编译期有用,在运行期无用

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

const 全局变量的分歧

现代编译器中(比如GCC),修改const全局变量将导致程序崩溃, 因为它存储于只读存储区(只读存储区的量不能修改)

注意:

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

#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;
}

编译条件  gcc version 5.4.0 输出

cc = 1
cc = 3
g_cc = 2
Segmentation fault (core dumped)

修改了 const 修饰的全局变量的值,导致程序崩溃

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(&i, 1);                 // warning
   // expected ‘int *’ but argument is of type ‘const int *
   // 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>
int main()
{
    const char* s = "Kevin zha";  // 字符串字面量
    
    return 0;
}

实验分析:

#include <stdio.h>
const char* f(const int i)
{
   // i = 5;                 // error
    
    return "Delphi Tang";
}

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

Volatile 关键字

  • volatile可理解为编译器警告指示字
  • volatile告诉编译器必须每次去内存中读取变量值
  • volatile主要修饰可能被多个线程访问的变量
  • volatile可以修饰可能被未知因数更改的变量
Const volatile int I =0;

特性:变量I 是只读变量 不能出现在赋值符号的左边(const) , 编译器每次都到内存中取值不做任何优化(volatile)

小结

  • const 使得变量具有只读属性
  • cosnt 不能定义真正意义上的的常量
  • 现代编译器中讲具有全局生命周期的变量存储于只读存储区
  • volitile 强制编译器减少优化,必需每次从内存中读取值

发布了84 篇原创文章 · 获赞 0 · 访问量 740

猜你喜欢

转载自blog.csdn.net/zhabin0607/article/details/103539186