参考博客:https://www.cnblogs.com/bianchengzhuji/p/10335837.html
const是constant的简写,是不变的意思。但并不是说它修饰常量,而是说它限定一个变量为只读。但是并非真正意义上的只读
1、看个例子1:
#include <stdio.h> int main(void) { // int num=10; // num=9; // printf("%d",num); // return 0; int a=9; int b=8; const int *p=&a; printf("%d",*p); }
输出:9
p是一个指向int类型的const值,与 int const *p等价
2、例子2:
#include <stdio.h> int main(void) { const int num=10; num=9; printf("%d",num); return 0; // int a=9; // int b=8; // const int *p=&a; // printf("%d",*p); }
报错:
C:\Users\xinhao\Documents\test01.c: In function 'main':
C:\Users\xinhao\Documents\test01.c:5:5: error: assignment of read-only variable 'num'
报错原因是num这个变量是只读的,强行num=9就会报错
3、例子3:
#include<stdio.h> void myPrint(const char *str); void myPrint(const char *str) { str[0] = 'H'; printf("my print:%s\n",str); } int main(void) { char str[] = "hello world"; myPrint(str); return 0; }
报错:
C:\Users\xinhao\Documents\test01.c: In function 'myPrint':
C:\Users\xinhao\Documents\test01.c:5:12: error: assignment of read-only location '*str'
str[0] = 'H';
报错原因是myPrint函数修改传入的字符串内容,因此入参使用了const限定符,表明传入的字符串是只读的,因此,如果myPrint函数内部如果尝试对str进行修改,将会报错
我们自己在编码过程中,如果确定传入的指针参数仅用于访问数据,那么应该将其声明为一个指向const限定类型的指针,避免函数内部对数据进行意外地修改
4、例子4:
#include <stdio.h> int main(void) { const int a = 2018; int *p = &a; *p = 2019; printf("%d\n",a); return 0; }
此时编译器给了个warring:
C:\Users\xinhao\Documents\test01.c: In function 'main':
C:\Users\xinhao\Documents\test01.c:5:14: warning: initialization discards 'const' qualifier from pointer target type
int *p = &a;
运行输出:2019
5、在a文件中定义,其他文件中使用外部声明
a文件中:const int ARR={1,2,3,4,5,6,7,8,9} //定义int数组
b文件中:extern const int ARR={1,2,3,4,5,6,7,8,9} //这里不能对ARR赋值
6、在a文件中定义,并使用static修饰,b文件包含a文件
a文件中:static const int ARR={1,2,3,4,5,6,7,8,9} //定义int数组
b文件中:#include<a.h>//后面可以使用ARR