3
#include <bits/stdc++.h>
using namespace std;

int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    auto arr = new int[5];
    // int arr[5] = {1, 2, 3, 4, 5};
    for (auto i: arr){
        cout << i << ' ';
    }
}

Why isn't this working? I am getting a compile time error saying this.

C.cpp: In function 'int main()':
C.cpp:8:15: error: 'begin' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
     begin(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
C.cpp:8:15: error: 'end' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'
     end(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'

When I initialized array in commented way, it works fine. (obviously) So, I think problem is with new operator. But I don't understand what it is.

George Hilliard
  • 15,402
  • 9
  • 58
  • 96
avamsi
  • 389
  • 3
  • 16
  • Because `arr` is an `int *`, not an array. In the code you have commented out, `arr` is an array, not a pointer. [Arrays are not pointers!](https://stackoverflow.com/q/4810664/241631) – Praetorian Jun 30 '15 at 04:09
  • There is of course `std::array` for the case of dynamically allocated arrays. – PeterSW Jun 30 '15 at 17:41

1 Answers1

9

new int[5] allocates an array of 5 elements and returns a pointer to the first element. The returned type is rvalue int*

int foo[5] is an array of 5 elements. The type of foo is lvalue int [5]

The range for loop requires it to know the size of the object it is iterating over. It can iterate over arrays, but it cannot iterate over pointers. Consider this code,

int foo[4];
for (int a : (int *)foo) {}

GCC 5.0 also produces an error "error: ‘begin’ was not declared in this scope" because the array was decayed into a pointer.

Quentin
  • 62,093
  • 7
  • 131
  • 191
user3427419
  • 1,769
  • 11
  • 15