Why can the "Range-based for loop" ( for (declaration:range) statement) be used only in the main function? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why can the "Range-based for loop" ( for (declaration:range) statement) be used only in the main function?

Range-based for loop

13th Jul 2019, 8:03 PM
Geral
8 Answers
+ 1
Solution 1 void range_for (string arr) { for (char c : arr) cout << c << endl; } template <size_t X> void range_for (int (&arr) [X]) { for (int c : arr) cout << c << endl; } int main () { string str {"Hello!"}; int a [] = {1, 2, 3}; range_for (str); //It works. for (int n : a) cout<< n << ' '; //It works range_for (a); // This function now uses the address of the array as well as its size.
13th Jul 2019, 10:03 PM
Geral
+ 1
Solution 2 Turn the array into a vector
13th Jul 2019, 10:04 PM
Geral
+ 1
Thanks, Checker 8763! I appreciate your help!
13th Jul 2019, 10:08 PM
Geral
+ 1
We might say that: "Range-based for loop could be used anywhere, just don't forget to work with a variable with a fixed size. If a function implements a range-based for loop inside and the argument used as range is an array, it will show an error, because the size information is lost."
13th Jul 2019, 10:17 PM
Geral
0
C++. I know they could be used anywhere, I'm just asking for this kind of syntax. Whenever I try to use it, an error shows up.
13th Jul 2019, 8:11 PM
Geral
0
Thanks! I'm trying this: void range_for (string arr) { for (char c : arr) cout << c << endl; } void range_for (int arr []) { for (int c : arr) cout << c << endl; } int main () { string str {"Hello!"}; int a [] = {1, 2, 3}; range_for (str); //It works. for (int n : a) cout<< n << ' '; //It works range_for (a); // error (''This Range-based for statement requires a suitable begin function and none was found'') }
13th Jul 2019, 9:03 PM
Geral
0
According to my research, the "range-based for" need the size of argument. Since passing an array as a function argument means passing a pointer to the first element and not the array itself, that fact leads to an error while using this kind of syntax.
13th Jul 2019, 9:58 PM
Geral
0
This is what I found: https://stackoverflow.com/questions/7939399/how-does-the-range-based-for-work-for-plain-arrays I'm sorry that I thought this question was simpler than it is. I'm not that perfect in c++ but I try to help at best!
13th Jul 2019, 10:03 PM
Checker 8763
Checker 8763 - avatar