1.ANSI C 允许声明常量,常量的样子和变量完全一样,只是它们的值不能修改,用const关键字来声明常量,如下所示:

int const a;
const int a;

以上语句是等价的。

2 常量的赋值

2.1 在声明的时候对它进行初始化:例如 int const a = 15;

2.2 在函数中声明为const 的形参在函数被调用时会用到实参的值。

#include <stdio.h>
int func(int const c)
{

	return c+c;
}
int main()
{
	int c;
	int sum;
        scanf("%d",&c);
	sum = func(c);
	printf("sum =%d\n",sum);
	return 0;
}

3.const和指针

当涉及指针变量时,有两样东西都可能称为变量---指针变量和她所指向实体。

3.1 int const  *pci:

这是一个指向×××常量的指针,此时可以把*p看做一个常量,可以修改指针(即p)的值,但是不能修改它所指向的值(*p),例如:

#include <stdio.h>

int main()
{
    int test1 = 1;
    int test2 = 2;
    int const *p ;
    p = &test1;
    p = &test2;      //p的值可以改变
    test2 = 10;     
//  *p = 100;   //错误,*p是常量,所以不能改变
    printf(" *p = %d\n",*p);
    return 0;
}

输出结果是:*p = 10

3.2 int * const pci 

声明pci为一个指向×××的的常量指针,此时指针是常量,它的值无法修改,但是可以修改它所指向的×××的值。

#include <stdio.h>

int main()
{
        int test1 = 1;
        int test2 = 2;
    int  * const p = &test1;

//      p = &test2;  //错误,因为p为常量
        test1 = 10;
        *p = 100;   //正确
        test1 = 3;
        printf(" *p = %d\n",*p);
        return 0;
}

输出结果是:*p = 3

4.总结

区别int const * p int * const p的方法是:看const的位置,如果const在*p的前面(int const *p),则 *p是常量,它的值不能被修改,但p可以重新赋值;如果const在p的前面,则p是常量,它的值不能被修改,但是*p可以重新赋值。