C语言 const 修饰之前学的稀里糊涂的,最近入了韦东山老师 百问网 7天物联网的课,跟学中结合范例终于基本搞清除了。
学习摘记和测试如下,共享给大家共同进步!
1)
修饰变量
const
修饰变量,功能是对变量声明为只读,并保护变量值以防被修改。例如:
const int i = 5;
// 或如下顺序也可以
int const i = 5;
示例中,i 为只读修改不了,重新赋值是错误用法,如试图改变i:i=100 ;
要注意的是,
const定义变量的同时还必须对其初始化!
此外,
const
修饰变量还起到了节约空间的目的,通常编译器并不给普通
const
只读变量分配空间,而是:
将它们保存在符号列表中,无需读写内存操作,程序执行效率也会提高。
2)
修饰数组
C
语言中
const
还可以修饰数组,例如:
const int array[5] = {0, 1, 2, 3, 4};
// 或
int const array[5] = {0, 1, 2, 3, 4};
//同样,不能修改,如下操作一定会报错:
array[2] = 1000;
测试代码:
int main(void)
{
const i = 5;
i = 100;
const int arry[5] = {0, 1, 2, 3, 4};
arry[2] = 1000;
return 0;
}
//vscode 终端报错 read-only variable...————————————————————————————————————————————————————————————————————————————————
tmp.c: In function 'main':
tmp.c:5:11: warning: type defaults to 'int' in declaration of 'i' [-Wimplicit-int]
const i = 5;
^
tmp.c:6:7: error: assignment of read-only variable 'i'
i = 100;
^
tmp.c:8:13: error: assignment of read-only location 'arry[2]'
arry[2] = 1000;
^
3)
修饰指针
C
语言中
const修饰指针需要特别注意,共有两种形式,一种是用来限定指向空间的值不可修改;另一种 是限定指针不可修改,例如:
int i = 5;
int k = 10;
int const *p1 = &i;
int * const p2 = &k;
const 修饰 *p1,是让 p1 指向的内存空间的值为只读,进行改变改地址的值就会报错,如:*p1=100 是错误操作;
const 修饰p2,是让 p2本身的地址值为只读,即p2修改不了,如进行改变p2的地址的操作,如:p2=&i 就会报错;
int main(void)
{
int i = 10;
int j = 100;
int const *p1 = &i;
int *const p2 = &j;
*p1 = 11;
p2 = &j;
return 0;
}
//vscode 中测试报错——————————————————————————————————————————————————————————————————
tmp.c: In function 'main':
tmp.c:10:9: error: assignment of read-only location '*p1'
*p1 = 11;
^
tmp.c:12:8: error: assignment of read-only variable 'p2'
p2 = &j;
4)
修饰函数参数
在
C
语言中
const修饰函数参数对参数起限定作用,防止其在函数内部被意外修改,所限定的参数可以是 普通变量也可以是指针变量,如:
void fun(const int x)
{
...
x = 10; // 对 x 的值进行了修改,错误
}
void fun1(const int *p)
{
...
(*p)++; // 对 p 指向空间的值进行了修改,错误
}