1.修饰变量
在变量前用const修饰,把变量声明为常量初始化后其值不能被修改
#include <stdio.h>
int main()
{
const short a = 200;//const修饰成常量后a的值不能被修改
short const b = 100;//short const b与 const short b等价
a = 50;//错误,const修饰a为常量,常量a的值不能修改
b = 10;//常量不能修改,编译时报错
printf("%d %d\n", a, b);
return 0;
}
2.修饰指针
(1)指针常量:const修饰p,表示p所指向的内存地址不可以改变,但可以改变p指向的变量的值
int a = 1;
int * const p = &a;
p++;//错误,const修饰指针p,p指向的变量的内存地址不能改变
printf("%d\n", *p);
int a = 1;
int * const p = &a;
*p = 2;//正确,const修饰指针p,p指向的变量的值可以改变
printf("%d\n", *p);
(2)常量指针:const修饰*p,表示p指针指向的变量的值不可以改变, 但可以改变p指向的内存地址
int a = 1;
int const * p = &a;
*p = 2;//错误,const修饰*p,*p的值不能被修改
printf("%d\n", *p);
int a = 1;
int const * p = &a;
printf("%p\n", p);
p++;//正确,p的指向的地址可以改变
printf("%p\n", p);
打印结果:指针偏移了4个字节,正好是一个int型变量占用的内存地址
0x7fffc8f3780c
0x7fffc8f37810
(3)const修饰*与p,表示p指向的变量的值与p指向的地址都不能改变,*是解引用,用于获取指针p指向的变量的值,p是指针指向某段内存地址
int a = 1;
const int * const p = &a;
*p = 2;//错误,p指向的变量的值不能改变
p++;//错误,p指向的地址也不能改变
3.修饰函数参数的指针形参
const char *str作为函数参数:*str被const修饰,它可以避免传递过来的值在函数体内部被错误修改
void printString(const char *str)
{
*str = "hello";//错误,const修饰*str,*str指向的变量的值不能被修改
printf("%s\n", str);
}
int main()
{
char s[] = "hello world!";
printString(s);
printf("%s\n", s);
return 0;
}
4.修饰函数返回值
#include <stdio.h>
const int getNum(int x)
{
return x = 5;
}
int main()
{
int a = 2;
int ret = getNum(a);
printf("ret = %d\n", ret);
return 0;
}
打印结果:
ret = 5
可以看出,getNum函数的返回值并没有被传递过来的实参a修改,因此,函数的返回值被const修饰后,可以确保函数的返回值在使用的过程中不会被修改
总结:
在c语言中,const关键字可以修饰变量、修饰指针、修饰函数,修饰函数参数
1.修饰变量
const int a,int const a,两者写法不同,意义是相同的
2.修饰指针
常量指针:const int *p,int const *p,两者写法不同,意义是相同的
指针常量:int * const p只有一种写法,修饰指针p,p的指向不能被修改
const int *const p:指针p的指向和指向的变量的值都不能被修改
3.修饰函数
函数返回值使用过程中无法被修改
const int getNum也可以写成int const getNum,两者的意义是相同的
4.修饰函数形参
修饰指针:指针常量与常量指针,看前面两个字。指针常量:指针p被const修饰,它的指向不能被修改;常量指针:变量被const修饰成常量,它的值不能被修改
总之,const靠近谁,谁就不能被修改