why this commented code don't work. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

8th Jan 2021, 3:48 AM
rajshekhar y dodamani
rajshekhar y dodamani - avatar
5 Answers
+ 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
8th Jan 2021, 6:37 AM
Arsenic
Arsenic - avatar
+ 3
rajshekhar y dodamani well that can also be a reason 😂
8th Jan 2021, 6:42 AM
Arsenic
Arsenic - avatar
+ 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
8th Jan 2021, 5:22 AM
Michal Doruch
+ 1
Some people might think blindly looking at the code, "It won't work because you commented it".
8th Jan 2021, 6:41 AM
rajshekhar y dodamani
rajshekhar y dodamani - avatar
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; }
9th Jan 2021, 6:08 PM
Sajid Ali
Sajid Ali - avatar