将指针参数声明为指向常量数据的指针有两条理由:
1、这样可以避免由于无意间修改数据而导致的编程错误;
2、使用 const使得函数能够处理 const和非 const实参,否则将只能接受非 const数据,如果条件允许,则应将指针形参声明为指向const的指针
void showArry(const int arr[], const int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main(void)
{
const int arr[] = { 10,15,12,24,45 };
int length = sizeof(arr) / sizeof(arr[0]);
showArry(arr, length);
return 0;
}
void showArry(const int arr[], const int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main(void)
{
int arr[] = { 10,15,12,24,45 };
int length = sizeof(arr) / sizeof(arr[0]);
showArry(arr, length);
return 0;
}
void showArry(int arr[],int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main(void)
{
int arr[] = { 10,15,12,24,45 };
int length = sizeof(arr) / sizeof(arr[0]);
showArry(arr, length);
return 0;
}
void showArry(int arr[],int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
int main(void)
{
const int arr[] = { 10,15,12,24,45 };
int length = sizeof(arr) / sizeof(arr[0]);
showArry(arr, length);
return 0;
}
总结:形参加上const后,实参可以为const和非const实参,斗则只能接受非const数据