Home  >  Article  >  Backend Development  >  How to Use Range-Based for-Loops on Arrays Passed to Non-main Functions in C ?

How to Use Range-Based for-Loops on Arrays Passed to Non-main Functions in C ?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 09:29:29791browse

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 (&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;
  }
}

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 (&amp;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!

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