C语言笔记11

109 阅读1分钟

const关键词

修饰数组元素

  • 禁止修改数组元素 只能读取 不能修改
  • 放在char左边或右边
const char str[20] = "hello\n";
char const str[20] = "hello\n";

修饰指针指向的数据

  • 同理 加了const关键词的指针指向的数据也是不能修改的
  • c++中强制要求指向字面字符串字面常量的指针为const char*
const char* pstr = "hello\n";

修饰指针本身

  • const此时修饰指针本身 即指针本身的值在初始化后无法修改了
  • 格式为char * const
char* const pstr = "hello\n";  

判断const修饰的部分

  • const在*左边 修饰所指向的数据

const char* pstr="hello\n"
char const* pstr="hello\n"//c++中达咩

  • const在*右边 修饰所指指针本身

char* const pstr="hello\n"

例子

    int i = 100;

    const int* p;
    p = &i;//正确 const修饰的是指针指向的值 而不是指针本身 给指针赋值可行 且没有放大操作权限(只读不写)
	
    int* const q;
    q = &i;//错误 const指向的是指针本身 在定义时就要对p初始化 后续不能再赋值

修饰基础变量

  • 只能读取不能修改
#include<stdio.h>
int main()
{
        const int i = 100;
        i = 101;//报错
        return 0
}