Home > Backend Development > C++ > body text

How to Use Range-Based For-Loops with Arrays Passed to Non-Main Functions in C ?

Barbara Streisand
Release: 2024-10-25 03:01:30
Original
118 people have browsed it

How to Use Range-Based For-Loops with Arrays Passed to Non-Main Functions in C  ?

Range-Based for-Loop on Array Passed to Non-Main Function

When passing an array as an argument to a non-main function, range-based for-loops may fail due to loss of size information. Here's how to resolve this issue:

In the provided code, when passing bar to foo, it decays into a pointer, losing its size. To preserve the array size, we can pass it by reference using an array reference type:

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

Alternatively, we can use a generic approach with a template function that automatically accepts arrays of any size:

<code class="cpp">template <std::size_t array_size>
void foo(int (&amp;bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}

int main() {
  int bar[3] = {1, 2, 3};
  for (int i : bar) {
    cout << i << endl;
  }
  foo(bar);
}</code>
Copy after login

By preserving the array size information, range-based for-loops can be used successfully when passing arrays to functions.

The above is the detailed content of How to Use Range-Based For-Loops with Arrays Passed to Non-Main Functions 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!