Home >Backend Development >C++ >How to Use Range-Based for-Loops on Arrays Passed to Non-main Functions in C ?
Range-based for-loop on Array Passed to Non-main Function
When assigning an array to a pointer in a function call, the compiler infers the pointer type and loses crucial information: the array size. This discrepancy triggers errors when attempting to perform range-based for-loops within the function.
To address this issue, one solution is to utilize an array reference instead of a pointer. By doing so, the function retains knowledge of the array's size:
<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, a generic approach can be employed by introducing a template parameter representing the array size:
<code class="cpp">template <std::size_t array_size> void foo(int (&bar)[array_size]) { for (int i : bar) { cout << i << endl; } }</code>
By leveraging these techniques, it becomes possible to successfully execute range-based for-loops on arrays passed to non-main functions.
The above is the detailed content of How to Use Range-Based for-Loops on Arrays Passed to Non-main Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!