Home > Backend Development > C++ > body text

How can I use a range-based for-loop on an array passed to a non-main function in C ?

Patricia Arquette
Release: 2024-10-25 06:57:02
Original
275 people have browsed it

How can I use a range-based for-loop on an array passed to a non-main function in C  ?

Range-based for-loop on array passed to non-main function

In C , a range-based for-loop can be used to iterate over an array. However, when an array is passed to a non-main function, it decays into a pointer, losing its size information.

To resolve this issue and enable the use of a range-based for-loop, the array should be referenced instead of being passed as a pointer. This retains the array's size information. Here are the modified examples demonstrating the correct approach:

<code class="cpp">void foo(int (&amp;bar)[3]);

int main() {
  int bar[3] = {1,2,3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}

void foo(int (&amp;bar)[3]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

// Generic implementation
template <std::size_t array_size>
void foo(int (&amp;bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}</code>
Copy after login

The above is the detailed content of How can I use a range-based for-loop 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!