参考博客: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=;
int b=;
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=;
num=;
printf("%d",num);
return ;
// 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[] = 'H';
printf("my print:%s\n",str);
}
int main(void)
{
char str[] = "hello world";
myPrint(str);
return ;
}

报错:

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 = ;
int *p = &a;
*p = ;
printf("%d\n",a);
return ;
}

此时编译器给了个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

最新文章

  1. inline-block元素间距
  2. [ASM C/C++] C语言函数的可选性自变量
  3. Nutch源码阅读进程4---parseSegment
  4. 那么如何添加网站favicon.ico图标
  5. 嵌入式 Linux下编译并使用curl静态库
  6. 我的PHP之旅--PHP的函数初步认识
  7. android Json解析详解
  8. OA项目总结
  9. [转]c++ new带括号和不带括号
  10. python基础===八大排序算法的 Python 实现
  11. javascript语法之声明变量
  12. 页面读取Excel
  13. 最小生成树(Prim算法)
  14. 洛谷P3722 [AH2017/HNOI2017]影魔(线段树)
  15. angularjs呼叫Web API
  16. 如何查看java进程
  17. ceil 和floor
  18. Watermelon -- codeforces
  19. Web app制作细节:web app互动制作技巧
  20. springboot 针对jackson是自动化配置

热门文章

  1. CSS3新单位vw,vh,vmin,vmax详解
  2. Git建立本地分支和远程分支的映射关系
  3. 量子计算机编程(二)——QPU基础函数
  4. 处理asp.net core连接mysql的一个异常Sequence contains more than one matching element
  5. freecplus框架,Linux平台下C/C++程序员提高开发效率的利器
  6. Azure CLI 简单入门
  7. MySQL字符集不一致导致性能下降25%,你敢信?
  8. python sqlite3操作类扩展,包含数据库分页
  9. 吃透这份pdf,面试阿里、腾讯、百度等一线大厂,顺利拿下心仪offer!
  10. C#的关键字Explicit 和 Implicit