Range Based For-loop on Array Passed to Non-Main Function
Question:
In a C project, an attempt to use a range-based for-loop on an array passed to a non-main function fails to compile. The code throws an error regarding the inability to find a matching function call for begin(int*&) while attempting to access the range-based for-loop in the non-main function.
Answer:
When you pass an array to a non-main function, the array decays into a pointer, losing crucial information about its size. To enable range-based for-loop within the non-main function:
Use Array Reference: Pass the array by reference instead of a pointer. This preserves the size information:
<code class="cpp">void foo(int (&&bar)[3]);</code>
Generic Approach: Use a function template with a template parameter specifying the array size. This approach allows for different array sizes to be passed:
<code class="cpp">template <std::size_t array_size> void foo(int (&&bar)[array_size]);</code>
By preserving the size information, the range-based for-loop can iterate over the array elements correctly within the non-main function.
The above is the detailed content of Why does a range-based for-loop fail when used on an array passed to a non-main function in C ?. For more information, please follow other related articles on the PHP Chinese website!