Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-25 02:15:29
Original
985 people have browsed it

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>
    Copy after login
  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>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!