auto function in c++

I was using auto function in my program when I got this error "Error: This range based for loop requires a begin function and none was found." How can I use for constant integers, as shown in my example below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
void printArr(int *arr,int size){
	for (auto &i:size){
		cout << arr[i] << " ";
	}
	cout << endl;
}
int main(){
	int arr[10] = {9,8,7,6,5,4,3,2,1};
	heapSort(arr, 0, (sizeof(arr) / sizeof(int)) - 1);
	int size = sizeof(arr) / sizeof(int);
	printArr(arr,size);
	getchar();
	return 0;
}
You can only use the ranged based loops with arrays when the size of the array is known (in the same scope as it was declared). When you pass an array to a function you can no longer use a range based loop, or the sizeof operator because you only have the address of the array available.

Note: the question is about range-based loop, unlike the thread title.

You do explicitly decay the array to a pointer and pointers do not know whether they have invalid address, address of one object, or address of one object that is in an array. The
1
2
3
4
5
6
7
8
9
for ( auto &i : size ) {
  std::cout << arr[i] << " ";
}

// is like writing
for ( auto it = std::begin(size); it != std::end(size); ++it ) {
  auto & i = *it;
  std::cout << arr[i] << " ";
}

It should be obvious why that has issues.

One can always use the older for syntax:
1
2
3
for ( int i = 0; i < size; ++i ) {
  std::cout << arr[i] << " ";
}


One could use algorithm and lambda to emphasize the for each element in array nature of the function:
1
2
std::for_each( arr, arr+size, []( auto x ) {
  std::cout << x << " "; } );



However, the way you do use the loop makes me guess that you are after pythonian range. That is not what the ranged for does, (but it could use). boost::irange is mentioned here:
http://stackoverflow.com/questions/1977339/c-range-xrange-equivalent-in-stl-or-boost
Last edited on
Understood. Thanks a lot @jib and @keskiverto
Topic archived. No new replies allowed.