以前对qualifier const的理解有很大的误区。
在 c专家编程中是这样描述的:
Const Isn't
The keyword const doesn't turn a variable into a constant! A symbol with the const
qualifier merely means that the symbol cannot be used for assignment. This makes the value
read -onl y through that symbol; it does not prevent the value from being modified through
some other means internal (or even external) to the program. It is pretty much useful only
for qualifying a pointer parameter, to indicate that this function will not change the data that
argument points to, but other functions may. This is perhaps the most common use of
const in C and C++.
关键字const并不能将一个变量转换成一个常量。一个带const限定符的符号仅仅是表示这个符号不能用于赋值。也就是说这个符号的值是只读的;const限定符不能阻止程序通过内部或者外部方法来修改这个值。const限定符最有用之处仅仅是限定实参指针,表示这个函数将不会改变实参指针指向的数据,但其他的函数可能会。这可能实const限定符在c和c++中最普遍的用法。
1:const限定符用在数据上。
2:用在指针上。
const和*的组合通常只用于模拟数组形式参数的按值传递,它声明:我给你一个指向它的指针,但你不可以改变它。
在 c专家编程中是这样描述的:
Const Isn't
The keyword const doesn't turn a variable into a constant! A symbol with the const
qualifier merely means that the symbol cannot be used for assignment. This makes the value
read -onl y through that symbol; it does not prevent the value from being modified through
some other means internal (or even external) to the program. It is pretty much useful only
for qualifying a pointer parameter, to indicate that this function will not change the data that
argument points to, but other functions may. This is perhaps the most common use of
const in C and C++.
关键字const并不能将一个变量转换成一个常量。一个带const限定符的符号仅仅是表示这个符号不能用于赋值。也就是说这个符号的值是只读的;const限定符不能阻止程序通过内部或者外部方法来修改这个值。const限定符最有用之处仅仅是限定实参指针,表示这个函数将不会改变实参指针指向的数据,但其他的函数可能会。这可能实const限定符在c和c++中最普遍的用法。
1:const限定符用在数据上。
const int a = 1;
表示a是只读的。
表示a是只读的。
2:用在指针上。
- cosnt int *p;
const限定符限定的是p指向的内容。
p指向一个只读的整形变量,不可以通过*p来改变其值。p本身是个变量。
p指向一个只读的整形变量,不可以通过*p来改变其值。p本身是个变量。
- int const *p; 与上面的是等价的。
- int * const p = &variable;
const限定符限定的是p,p的值是只读的。
- const int *cosnt p = &variable;
第一个const限定符限定的是p指向的内容,不可以通过*p来改变其值。
第二个const限定符限定的是p, p的值是只读的。
第二个const限定符限定的是p, p的值是只读的。
const和*的组合通常只用于模拟数组形式参数的按值传递,它声明:我给你一个指向它的指针,但你不可以改变它。