c语言【const】用法

1.const可用于保护数据:如下例程序所示,可保护数组不被show_array函数改变其值。

 1 #include<stdio.h>
 2 #define SIZE 5
 3 void show_arry(const double ar[], int n);
 4 void mult_array(double ar[], int n, double mult);
 5 int main(void)
 6 {
 7     double dip[SIZE] = { 20.0,3.2,5.3,63.0,6.3 };
 8 
 9     printf("the original dip array:\n");
10     show_arry(dip, SIZE);
11     mult_array(dip, SIZE, 5.0);
12     printf("the dip array after callling mult_array():\n");
13     show_arry(dip, SIZE);
14 
15     return 0;
16 }
17 
18 
19 void show_arry(const double ar[], int n)
20 {
21     int i;
22     for (i = 0; i < n; i++)
23         printf("%8.3f", ar[i]);
24     putchar('\n');
25 }
26 
27 void mult_array(double ar[], int n, double mult)
28 {
29     int i;
30     for (i = 0; i < n; i++)
31         ar[i] *= mult;
32 
33 }
 
2.
double rates[3]={2.3,3.1,56.0};
const double *pd =rates;
中,不可使用pd 改变它指向的值:
*pd=29.89;   //不允许
pd[2]=22.13;  //不允许
rates[0]=22.33; //允许,因为rates未被const限定
但可以让指针指向别处,即:
pd++;      //允许
3.指向const的指针一般用于函数形参当中,表示函数不会使用指针改变数据:
void show_array(const double *ar,int n);
1)把const数据或非const 数据的地址初始化为指向const的指针或为其赋值是合法的:。
2)只能把非const数据的地址赋给普通指针。
 
4.
double rates[3]={2.3,3.1,56.0};
double const *pc=rates;
中,声明并初始化一个不可以指向别处的指针,即:
pc++;  //不允许
但是可以改变其指向的值:
*pc=50.2 //允许
 
5.
double rates[3]={2.3,3.1,56.0};
const double const *pb=rates;
中,该指针既不能改变其指向的值,也不能改变其指向,即
pb=&rate[1]; //不允许
*pb=3.0;  //不允许

猜你喜欢

转载自www.cnblogs.com/bingger/p/11110275.html