常量不能被赋值,即 不能在 赋值符号"="的左侧.
常量指针,指向常量的指针.
数组类似于const 类型的指针
若const在前面 则 *xx = xxxx 不合法.若 *在前面 则 xx=&xxx不合法
1.const char *类型
#include<stdio.h>
main()
{
const char *str="test1";//每个字符都是const类型
printf("%s\n",str);
str="test2";
printf("%s\n",str);
// str[0]='w'; 非法语句
// *str='w'; 非法语句
}
start without debugging
2.char * const类型
#include<stdio.h>
main()
{
char * const str="test1";//指针为const类型,即 固定数值的指针
printf("%s\n",str);
// str="test2"; 非法语句
str[0]='w'; //部分系统因数据实际存放位置导致无法改变数值.部分编译器显示为不合法语句
printf("%s\n",str);
}
start without debugging
3.非const转const
给函数传参数时使用,可以避免 传递的参数 比地址大 的问题:
既能以较少的字节数给参数传值,还能防止函数对外部变量的修改.
4.const数组
数组类似于 * const ,那如果在数组前再加 const 呢?
结果时数组的每个元素的值都无法再被改变,
这样的数组若要赋值,应当在声明的同时完成初始化赋值.
同样我们可以在函数形参的地方使用 const数组类型 让数组在函数内得到保护
5.数组与* const的异同
#include<stdio.h>
int main()
{
int f(int c[],int * const d);
int a[5] = {1,2,3,4,5},b[5]= {6,7,8,9,10};
int * const p = b;
// p 初始化的是地址
//a 初始化的是 实际的值
printf("%d %d \n",sizeof(a),sizeof(p));
f(a,b);
}
int f(int c[],int * const d)
{
printf("%d %d \n",sizeof(c),sizeof(d));
//作为参数都是地址
}