Range-Based for-Loop on Array Passed to Non-Main Function
When passing an array as an argument to a non-main function, range-based for-loops may fail due to loss of size information. Here's how to resolve this issue:
In the provided code, when passing bar to foo, it decays into a pointer, losing its size. To preserve the array size, we can pass it by reference using an array reference type:
<code class="cpp">void foo(int (&bar)[3]); int main() { int bar[3] = {1, 2, 3}; for (int i : bar) { cout << i << endl; } foo(bar); } void foo(int (&bar)[3]) { for (int i : bar) { cout << i << endl; } }
Alternatively, we can use a generic approach with a template function that automatically accepts arrays of any size:
<code class="cpp">template <std::size_t array_size> void foo(int (&bar)[array_size]) { for (int i : bar) { cout << i << endl; } } int main() { int bar[3] = {1, 2, 3}; for (int i : bar) { cout << i << endl; } foo(bar); }</code>
By preserving the array size information, range-based for-loops can be used successfully when passing arrays to functions.
The above is the detailed content of How to Use Range-Based For-Loops with Arrays Passed to Non-Main Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!