一、const
1:修饰普通变量,代表只读的意思
const int a=100;//定义了一个只读变量a的值为100
以后在程序中,不能给a赋值了
a=20;//错误的,a只读
例子:
#include <stdio.h>
int main(int argc,char *argv[])
{
const int a=100;
a=200;
printf("%d\n",a);
return 0;
}
gcc编译的结果如下
gec@ubuntu:/mnt/hgfs/share/C语言/day11(8.29)/code$ gcc demo.c
demo.c: In function ‘main’:
demo.c:5:2: error: assignment of read-only variable ‘a’(报错,只读,不能修改)
2:const 修饰指针
(1)const char *str;
意思是str指向的内存的内容不能通过str来修改
用来保护str所指向的内容
(2)char *const str;
意思是str是只读的变量,str不能指向别的地方
(3)const char *const str;
str不能指向别的地方,指向的内存的内容也不能通过str去修改
(4)例子1:const char *str;即指向可以改,指向的内容不可以改
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
char buf[20]="hello world";
const char* str=buf;
strcpy(str,"hellokitty"); //错误
str="hellokitty";//正确
printf("buf=%s\n",buf);
return 0;
}
//(1)第一种情况
//没有加const修饰,使用strcpy是以修改buf数组里面的内容
//gec@ubuntu:/mnt/hgfs/share/C语言/day11(8.29)/code$ ./a.out
//buf=hellokitty
//(2)第二种情况
//有加const修饰,编译结果如下:
(5)例子2:char *const str;即指向不能改变,指向的内容可修改
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
char buf[20]="hello world";
char* const str=buf;
//strcpy(str,"hellokitty"); //正确
//*str='w'; //正确
//str="hellokitty"; //错误
printf("buf=%s\n",buf);
return 0;
}
(6)例3:const char *const str;即指向不能改,指向的内容也不能改
#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{
char buf[20]="hello world";
const char* const str=buf;
//strcpy(str,"hellokitty");//错误
//*str='w'; //错误
str="helloki