//部份内容参考 http://www.bccn.net/Article/kfyy/cyy/jszl/200607/4166.html
1.为了防止传递的函数参数不被修改,在调用函数的形参中用const关键字
int FindNum(const int array[], int num, int conut);//声明函数 //code... int FindNum(const int array[], int num, int count) { int i; int flag = 1; for (i = 0; (i < count) && flag; i++) { if (array[i] == num) { flag = 0; break; } } return flag; } //code...
2.const可以用来创建数组常量、指针常量、指向常量的指针等:
- const char ch = 'a';
const int a[5] = {1, 2, 3, 4, 5};
#include <stdio.h> void main(){ const int a=5; a=10; // error:specifies const object printf("%d\n",a); }
- const int *p = a;
#include <stdio.h> void main(){ int a[5] = {1, 2, 3, 4, 5}; int b[5] = {6, 7, 8, 9, 10}; const int *p = a; int i ; //遍历数组 a for(i=0;i<5;i++,p++){ printf("%d\t",*p); } printf("\n"); //*p=1; //error:specifies const object p=b; // 遍历数组 b for(i=0;i<5;i++,p++){ printf("%d\t",*p); } printf("\n"); }
p*=1编译出错: error:specifies const object
const int *p = a;
结论: 该指针变量可以被赋值多次,不能修改它所指向的元素的值,可以访问它所指向数组里的所有元素,
- int * const p = a;
#include <stdio.h> void main(){ int a[5] = {1, 2, 3, 4, 5}; int * const p = a; int i; for(i=10;i<15;i++){ *p=i; printf("%d\t",*p);// 结果:10 11 12 13 14 //p++; //error:specifies const object } printf("\n"); //遍历数组a for(i=0;i<5;i++){ printf("%d\t",a[i]); //结果: 14 2 3 4 5 } printf("\n"); p=&a[1];//error:specifies const object }
int * const p = a;结论: 该指针变量只能被赋值一次,且只能读取及修改它所指向的元素的值,不可以访问数组中的其它元素,
- const int * const p = a;
#include <stdio.h> void main(){ int a[5] = {1, 2, 3, 4, 5}; const int * const p = a; //*p=6;//error:specifies const object //p++;//error:specifies const object printf("%d\n",*p);//结果:1 }
const int * const p = a;
结论:该指针变量只能被赋值一次,只能读取它所指向的元素的值,不可修改值,不可以访问数组中的其它元素