作为数组索引的C++传递函数不起作用。

问题描述:

为什么以下两个代码给出不同的结果? 第一个打印零,而第二个打印随机计数如预期。 使用gcc 4.6.3作为数组索引的C++传递函数不起作用。

8 int foo(){ 
    9 return rand() % 2; 
10 } 
11 
12 int main() 
13 { 
14 int ar[2] = {0};    
15 for (int i = 0; i < 20; i++) { 
16 // int tmp = foo(); 
17 // ar[tmp]++; 
18  ar[foo()]; 
19 } 
20 
21 for (int i = 0; i < 2; i++) 
22  cout << i << " : " << ar[i] << endl; 
23 } 


8 int foo(){ 
9 return rand() % 2; 
10 } 
11 
12 int main() 
13 { 
14 int ar[2] = {0};    
15 for (int i = 0; i < 20; i++) { 
16  int tmp = foo(); 
17  ar[tmp]++; 
18  // ar[foo()]; 
19 } 
20 
21 for (int i = 0; i < 2; i++) 
22  cout << i << " : " << ar[i] << endl; 
23 } 
+0

你打算用'ar [1]'初始化什么值? – vonbrand 2013-02-16 20:33:34

因为你实际上并没有增加数组中的值:

ar[foo()]++; 
//  ^
// You forgot this 

这意味着所有的元素保持不变,你得到0作为你的输出。