- 如果對象不是針對,它們沒有區別
int const x = 3;
const int x = 3;
- 如果對象是指針,它們有區別
int* const p = &array
: 指針p不能夠指向其他地址
const int* p = &array
: 指針p只讀&array
,不能夠對其進行修改
舉例,
#include <iostream>
using namespace std;
int main()
{
int arr[3]={1,2,3};
int varr[3]={100,200,300};
const int* p1 = arr;
int* const p2 = arr;
cout << *p1 << endl;
cout << *p2 << endl;
// *p1 = 22; // error
*p2 = 22;
cout << *p2 << endl;
cout << arr[0] << endl;
p1 = varr;
cout << *p1 << endl;
p2 = varr;//error
return 0;
}