首页  >  文章  >  后端开发  >  如何在传递给 C 中非主函数的数组上使用基于范围的 for 循环?

如何在传递给 C 中非主函数的数组上使用基于范围的 for 循环?

Patricia Arquette
Patricia Arquette原创
2024-10-25 06:57:02276浏览

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

传递给非主函数的数组上基于范围的 for 循环

在 C 中,基于范围的 for 循环可以是用于迭代数组。但是,当数组传递给非主函数时,它会衰减为指针,从而丢失其大小信息。

为了解决此问题并启用基于范围的 for 循环,数组应该被引用而不是作为指针传递。这保留了数组的大小信息。以下是演示正确方法的修改示例:

<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>

以上是如何在传递给 C 中非主函数的数组上使用基于范围的 for 循环?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn