+ 2
why this commented code don't work.
I have written a program for using range based for loop in c++. It is working in same function where the array is declared but not when array is passed to another function. https://code.sololearn.com/c2A20A18A23A/#cpp
5 Respostas
+ 6
The problem here is that range based for loops are ment to run on arrays and not on pointers because they use std::begin and std::end iterators under the hood.
If you are familiar with C/C++, you would be knowing that here you are not passing entire array to the function, but passing the pointer pointing to the first element instead.
To fix the problem either use a 'conventional' for loop or pass the array as reference
Here is the fix using passing by reference👇
https://code.sololearn.com/cMFQWgx768Y1/?ref=app
+ 3
rajshekhar y dodamani well that can also be a reason 😂
+ 1
I'm not 100% sure about that, but probably builtin arrays don't work because they don't keep track of their size and don't have member functions which are required for the range based for loops to work. You can use STL array<> container instead, or just put those values in a vector so everything should work well
+ 1
Some people might think blindly looking at the code, "It won't work because you commented it".
0
// itsworking
#include<iostream>
using namespace std;
int arr[]={1,2,3,3,4,4,5,8};
/*void print(int arr[]){
for(int i:arr){
cout<<i<<endl;
}
}*/
int main(){
//print(arr);
for(int i:arr){
cout<<i<<endl;
}
return 0;
}