const本身是定义常量的,比如
const int buffSize = 512;
那么这个常量能否被一个整数指针引用呢,比如:
int *ptr = &buffSize;
由于编译器的局限性(不能跟踪程序在任意一点指向的对象,这个需要数据流分析),这个编译无法通过。那么这么办呢,就是定义一个常量指针:
const int *ptr;
常量可以常量指针引用,但是不能被修改。同时常量指针也可以指向变量,但是不能通过指针修改该变量:
ptr = &buffSize; //ok
int size = 16;
ptr = &size; //ok
*ptr = 17; // will cause an error
可以看出常量指针就是为const量身度作的。
现在转过来看这个函数定义:
int strcmp(const char* str1, const char* str2);
这里是什么意思呢?在实际的程序中,指向const的指针被当作形式参数,它作为一个约定来保证,被传递给函数的实际对象不会在程序中被修改。
最后,如果想定义一个完完全全的常量指针怎么做呢?如下:
const double PI = 3.14159265;
const double *const ptr = Π
一个相关参考程序:
/*************** begin of constPtr.cpp*******************/
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
const double PI = 3.14158265;
const double *ptr;
ptr = &PI;
cout << "The value of pointer /"ptr/" is " << *ptr << endl;
double radius = 3.0;
double area = PI * radius * radius;
ptr = &area;
cout << "The value of pointer /"ptr/" is " << *ptr << endl;
/******* test const ptr***********/
const double *const p2 = & PI;
cout << "The value of p2 is " << *p2 << endl;
/*
p2 = &area; // will cause an error here
cout << "The value of p2 is " << *p2 << endl;
*/
return 0;
}
/*************** endof constPtr.cpp*******************/
/***************build: g++ -o constPtr constPtr.cpp*******/