C语言 第9课 const和volatile分析

const 只读变量

  • const 修饰的变量是只读的,本质还是变量
  • const 修饰的局部变量上分配空间
  • const 修饰的全局变量全局数据区分配空间【标准C】
  • const 只在编译期有用(只能出现在赋值符号左边),在运行期无用

const 全局变量的分歧

  • 现代C语言编译器中,具有全局生命周期的 const 变量将被存储于只读存储区,修改将导致程序崩溃【GCC,VC】
  • 标准C语言编译器中,具有全局生命周期的 const 变量将被存储于全局数据区,其值仍然可以改变

编程实验: 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;
}
输出:【GCC 编译无警告】
cc = 1
cc = 3
g_cc = 2
Segmentation fault

const 的本质

  • C语言中的 const 使得变量具有只读属性
  • 现代C编译器中将 const 具有全局生命周期的变量存储于只读存储区
  • 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;
}
输出:
i = 1
j = 0
array[0] = 3
g_array[0] = 0
  • const 修饰函数参数和返回值
    • const 修饰函数参数表示在函数体内不希望改变参数的值
    • const 修饰函数返回值表示返回值不可改变,多用于返回值指针的情形

小贴士 : C语言中的字符串字面量存储于只读存储区中,在程序中需要使用const char* 指针
const char* s = "D.T.Software"

实例分析: const 修饰函数参数与返回值

#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;
}
输出:
i = 5.
D.T.Software

深藏不露的 volatile

  • volatile 可立即为 编译器警告指示字,禁止编译器的优化
  • volatile 告诉编译器必须每次去内存中取变量值
  • volatile 主要修饰可能被多个线程访问的变量或者被中断处理函数访问的变量
  • volatile 也可以修饰被未知因数改变的变量
void code()
{
    int obj = 100;
    
    int a = 0;
    int b = 0;
    
    a = obj;
    sleep(100);
    b = obj;
}
  • 编译器做了什么?
    • 编译器在编译时发现obj没有被当成左值使用,因此会"聪明"的直接替换成10,而把a和b都赋值为10。
    • 因为编译器会自作聪明不去在读取内存,如果是多线程的编程或者有中断,当a = obj;以后在中断或者另一个线程里面改变了obj的值,那么之后b=obj;得到的不是想要的值。
  • 有趣的问题
const volatile int i = 0;
变量 i 具有什么样的特性?
编译器如何处理这个变量?

答: i 为只读变量,不能出现在赋值符号的左边;同时,每次操作,都需要到内存中取值

小结

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值