const关键字的常用用法

c语言中const关键字的常用用法

1.const关键字的意思

const 是 constant 的缩写,恒定不变的、常数;恒量

它是定义只读变量的关键字,或者说 const 是定义常变量的关键字。

2.用法试例

2.1修饰普通变量


const int i = 1<==> int const i = 1;
代码段
#include<stdio.h>

int main(void){
	const int i = 1;
	i = 6;
	printf("i=%d",i);
	return 0;
}
gcc const.c
报错:const.c: In function ‘main’:
const.c:6:4: error: assignment of read-only variable ‘i’
  i = 6;
    ^
结论:const修饰普通变量,即不允许给它重新赋值,即使是赋相同的值也不可以。代表只读变量

2.2修饰数组

#include<stdio.h>

int main(void){
	const int arr[] = {2,2,2};
	arr[2] = 3;
	printf("i=%d",arr[2]);
	return 0;
}
编译报错
const-array.c: In function ‘main’:
const-array.c:6:9: error: assignment of read-only location ‘arr[2]’
  arr[2] = 3;
         ^
 结论:const修饰数组,那么相当于里面的每个变量都被const修饰

2.3修饰指针

#include<stdio.h>
//1.const 在*前面
int main(void){
    int a = 10;
	int b = 20;
	const int* p = &a;//<==> int const *p = &a;这两个写法一样的意思
	printf("a=%d",a);
    printf("b=%d",b);
	printf("p=%p",p);
	//*p = 10;//这一行报错
	p = &b;
	printf("p=%p",p);
    printf("*p=%d",*p);
		
	return 0;
}
//2.const 在*后面,
int main(void){
    int a = 10;
	int b = 20;
	int* const p = &a;
	printf("a=%d",a);
    printf("b=%d",b);
	printf("p=%p",p);
	*p = 10;
	//p = &b;//这一行报错
	printf("p=%p",p);
    printf("*p=%d",*p);
		
	return 0;
}

//3.
int main(void){
    int a = 10;
	int b = 20;
	const int* const p = &a;
	printf("a=%d",a);
    printf("b=%d",b);
	printf("p=%p",p);
	//*p = 10;报错
	//p = &b;//这一行报错
	printf("p=%p",p);
    printf("*p=%d",*p);
		
	return 0;
}


结论:
1.const*前面,那么该指针对应值不能变,意思就是该地址的值不变,但是p这个变量是可以变的,p可以重新指定为b的地址,人称常量指针
2.const*后面,代表const修饰变量p,那么p这个变量不能变,p又代表一个指针,是可以修改对应地址的值,人称指针常量
3.两个const这种情况代表p这个变量不能被修改,p对应地址的值也不能被修改
4.可以通过指针对第一种情况的值进行求改,但是在我这种环境编译器会警告,可以变异通过,这样子破坏了i的只读属性
const.c:7:14: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
     int* p = &i;
5.特别的对下面这段代码,指针数组(里面全是指针的数组,是数组)
	int a = 10;
    int b = 20;
    const int* arr[] = {&a,&b};
    *(arr[0]) = 100;//报错,相当于 const int* p;

2.4修饰函数的参数

//如如,那么表明a这个临时变量不能被修改
int add(const int a){
    //a = 10;报错
}

3.总结

1.其他情况还未使用过
2.略,见上demo

本文测试环境

deppin系统15.11,gcc版本gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)

发布了47 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43328357/article/details/104932892
今日推荐