"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I use a range-based for-loop on an array passed to a non-main function in C++?

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

Published on 2024-11-08
Browse:166

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:

void foo(int (&bar)[3]);

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

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

// Generic implementation
template <std::size_t array_size>
void foo(int (&bar)[array_size]) {
  for (int i : bar) {
    cout << i << endl;
  }
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3