void main()
{
//int const i ; //const object must be initialized if not extern。变量const i如果不是一个外部变量(extern),在声明时必须初始化。(1)
int const i = 5;
int *pi;
int const *cpi; //可以不初始化
int * const pci = NULL; //必须初始化
int a, b /* c */;
pi = &a;
cpi = &b;
//*cpi = 10; //error : *cpi's value is const, cannot be modified。 cpi是个指针变量,而*cpi是个常量被修饰为const不可变,故给*cpi赋值会报错 (2)
cpi = &a; //correct: cpi is a value can be modified 。cpi是个变量值可以被修改。
cpi = &b;
*pci = 10; //correct
// pci = &a; //error: pci can not be modified。pci是一个const变量,不可变,而他指向的值可变。
const int *p1; //.c文件这样写编译不通过,.cpp可以.在VC6.0下const int *p1和int const *p2编译不通过,CODEBLOCKS就可以编译
int const *p2;
Use the const modifier to make a variable value unmodifiable.
Use the const modifier to assign an initial value to a variable that cannot be changed by the program.
Any future assignments to a const result in a compiler error.
A const pointer cannot be modified, though the object to which it points can be changed.
Consider the following examples.
const float pi = 3.14;
const maxint = 12345; // When used by itself, const is equivalent to int.
char *const str1 = "Hello, world"; // A constant pointer
char const *str2 = "Borland International"; // A pointer to a constant character string.
Given these declarations, the following statements are legal.
pi = 3.0; // Assigns a value to a const.
i = maxint++; // Increments a const.
str1 = "Hi, there!" // Points str1 to something else.
Using the const Keyword in C++ Programs
C++ extends const to include classes and member functions.
In a C++ class definition, use the const modifier following a member function declaration.
The member function is prevented from modifying any data in the class.
A class object defined with the const keyword attempts to use only member functions
that are also defined with const.
If you call a member function that is not defined as const,
the compiler issues a warning that the a non-const function is being called for a const object.
Using the const keyword in this manner is a safety feature of C.
Warning: A pointer can indirectly modify a const variable, as in the following:
*(int *)&my_age = 35;
If you use the const modifier with a pointer parameter in a function's parameter list,
the function cannot modify the variable that the pointer points to. For example,
int printf (const char *format, ...);
printf is prevented from modifying the format string.