Home  >  Article  >  Backend Development  >  Why does a range-based for-loop fail when used on an array passed to a non-main function in C ?

Why does a range-based for-loop fail when used on an array passed to a non-main function in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 02:15:29986browse

Why does a range-based for-loop fail when used on an array passed to a non-main function in C  ?

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:

  1. 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>
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn