Reputation: 127
The following code correctly outputs the elements of an array for the first two for statements, but in the third it incorrectly outputs the elements of the array from a range based for loop when using cout (works with printf in the first). Why is this?
#include <iostream>
using namespace std;
int main( int argc, char ** argv )
{
int myArray[]={10,20,30,40,50};
for (int i : myArray) {
printf("%d\n", i);
}
for (int i = 0 ; i < 5; i++) {
cout << myArray[i] << endl;
}
for (int i : myArray) {
cout << myArray[i] << endl;
}
return 0;
}
the output:
10
20
30
40
50
10
20
30
40
50
-1707465271
0
1606417258
1606417820
1606418039
Upvotes: 0
Views: 82
Reputation: 217085
You have out of bound access in
for (int i : myArray) {
cout << myArray[i] << endl;
}
as i
would be 10,20,30,40,50.
you want
for (int i : myArray) {
cout << i << endl;
}
as you do with printf
.
Upvotes: 4
Reputation: 15824
You dont need to use index variable while using range based for loop, instead you need a local variable to retrieve the data from container or array that you need to loop
for (int i : myArray) {
cout << myArray[i] << endl;
}
The above snippet of code should correct as follows:
for (int i : myArray) {
cout << i << endl;
}
Upvotes: 0
Reputation: 310930
Change it the following way
for (int i : myArray) {
cout << i << endl;
}
It is the same loop as you wrote before it with using printf
for (int i : myArray) {
printf("%d\n", i);
}
Take into account that you should include header <cstdio>
Upvotes: 1