定数(int const*pとint*const p)


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
",sum); return 0; }

3.constとポインタ
ポインタ変数に関連する場合、ポインタ変数と彼女が指すエンティティの2つのものを変数と呼ぶことができます.
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
",*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
",*p);         return 0; }

出力結果:*p=3
4.まとめ
int const*pとint*const pを区別する方法は、constの位置を見て、*pの前にconstがある場合(int const*p)、*pは定数であり、その値は修正できないが、pは再付与できる;constがpの前にある場合、pは定数であり、その値は修正できないが、*pは再付与できる.