这小段文章要理清楚的是,在C语言中, c o n s t const const是如何保证变量不被修改的?
我们可以想到两种方式:
第一种,由编译器来阻止修改 c o n s t const const变量的语句,让这种程序不能通过编译;
第二种,由操作系统来阻止,即把 c o n s t const const 的内存地址访问权限标记为“只读”,一旦运行中的程序试图修改它,就会产生异常,终止进程。
先来看一个简单的例子,源文件const.c:
#include <stdio.h>
const int a=10;
int main()
{
int *p=&a;
printf("initial: %d\n",a);
*p=1;
printf("modified: %d\n",a);
return 0;
}
编译,会收到一个 warning:
$ gcc -o const1 const1.c
const.c: In function ‘main’:
const.c:7:12: warning: initialization discards ‘const’ qualifier from pointer target