【发布时间】:2014-11-03 03:45:43
【问题描述】:
这段代码在不使用 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 }
- 代码参考:MIT C++ Open Course Lecture Note 4 “Arrays and Strings”
- 网址:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-096-introduction-to-c-january-iap-2011/lecture-notes/MIT6_096IAP11_lec04.pdf
【问题讨论】:
-
更好的问题:“这段代码用 const 编译和执行得很好,这里不使用 const 有什么特殊原因吗?”。
-
@JonathanDursi:不是重复的,因为没有
const T xx[]形式的参数,只有const T询问。 -
@Deduplicator :我看到了这个论点,但是对这个问题的回答特别提出了指针、引用等问题。这个问题没有理由独立存在,尽管肯定有是一个更好的 dup 建议。