Range based for loop and arrays - Bug!
Feb 7, 2017 at 2:14am UTC
I know there is an alternative to this code which I have already provided, but is there any way to fix the bug with the range based for loop ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#include <iostream>
using namespace std;
void print(const int score [], const int size){
for (int x : score){
cout << x << " " ;
}
// Alternative:
// for (int i = 0; i < size; i++){
// cout << score[i] << " ";
// }
}
int main(){
int score[] = {1, 2, 3, 4, 5};
int size = sizeof (score)/sizeof (int );
print(score, size);
return 0;
}
Feb 7, 2017 at 3:04am UTC
Feb 7, 2017 at 3:34am UTC
Just use a vector, they were invented to solve the problems that ordinary arrays have. As I said before don't mix C and C++.
Feb 7, 2017 at 5:32am UTC
> is there any way to fix the bug with the range based for loop ?
The simplest fix is to let the compiler figure out what the sequence in question is, and the type of values it holds.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
template < typename SEQUENCE > void print( const SEQUENCE& /* SEQUENCE&& */ sequence ) {
for ( const auto & /* auto&& */ value : sequence ) std::cout << value << ' ' ;
std::cout << '\n' ;
}
int main() {
const int score[] = { 1, 2, 3, 4, 5 };
print(score);
}
Topic archived. No new replies allowed.