这段代码在不使用const的情况下编译和执行.在这里使用const有特殊原因吗?
0 #include <iostream>
1 using namespace std;
2
3 int sum(const int array[], const int length) {
4 long sum = 0;
5 for(int i = 0; i < length; sum += array[i++]);
6 return sum;
7 }
8
9 int main() {
10 int arr[] = {1, 2, 3, 4, 5, 6, 7};
11 cout << "Sum: " << sum(arr, 7) << endl;
12 return 0;
13 }
Run Code Online (Sandbox Code Playgroud)
你const用来实现const正确性.这意味着您已告诉编译器(以及您的代码的任何读者)所有不会自行更改的内容或它们所使用的对象.你已经为args做了这个sum,正确地说它们没有在函数中改变.你之所以这么做是因为它让代码更容易理解(对于读者来说)并且为编译器开辟了优化的可能性.
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |