const和volatile分析
1、const只读变量
- const修饰的变量是只读的,但本质上还是变量
- const只在编译期有用,在运行期无用

代码实践:
#include <stdio.h>
int main(void)
{
int cc = 10;
printf("cc == %d\n",cc);
int *p = (int *)&cc;
*p = 0;
printf("cc == %d\n",cc);
return 0;
}
输出结果为:

2、const全局变量的分歧
在现代C语言编译器中,修改const修饰的全局变量将导致程序奔溃,因为现代C语言编译器会将
const修饰的全局变量优化存储到只读变量区;

代码实践:
#include <stdio.h>
const int g_cc = 10;
int main(void)
{
printf("g_cc == %d\n",g_cc);
int *p = (int *)&g_cc;
*p = 0;
printf("g_cc == %d\n",g_cc);
return 0;
}
输出结果为:

3、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;
}
4、const修饰函数参数和返回值
- const修饰函数参数表示在函数体内不希望改变参数的值
- const修饰返回值表示返回值不可改变,多用于返回指针的情形

5、volatile
- volatile可理解为“编译器警告指示字”
- volatile告诉编译器必须每次去内存中取变量值
- volatile主要修饰被多个线程访问的变量或者可能被未知因素修改的变量

上述代码片段在多线程中,可能会出错
6、小结

本文深入探讨了C语言中的const和volatile关键字。解析了const修饰变量的只读特性及其在现代编译器中的实现机制,同时分析了volatile如何指示编译器每次从内存中获取变量值,适用于多线程环境。
694

被折叠的 条评论
为什么被折叠?



