Bug 54299 - Array parameter does not allow for iterator syntax
Array parameter does not allow for iterator syntax
Status: UNCONFIRMED
Product: gcc
Classification: Unclassified
Component: middle-end
4.7.0
: P3 normal
: ---
Assigned To: Not yet assigned to anyone
:
Depends on:
Blocks:
  Show dependency treegraph
 
Reported: 2012-08-17 15:26 UTC by Ulrich Drepper
Modified: 2012-08-17 15:43 UTC (History)
0 users

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Ulrich Drepper 2012-08-17 15:26:07 UTC
Compile the following code:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int aa[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

int f(int arr[10])
{
  int s = 0;
  for (auto i : arr)
    s += i;
  return s;
}

int main()
{
  return f(aa);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This fails with

u.cc: In function ‘int f(int*)’:
u.cc:18:17: error: ‘begin’ was not declared in this scope
u.cc:18:17: error: ‘end’ was not declared in this scope
u.cc:18:17: error: unable to deduce ‘auto’ from ‘<expression error>’



This indicates that the problem is that the parameter is seen as 'int *' instead of as 'int [10]'.  According to Andrew another problem caused by the too-early decay of arguments to pointers (bug 24666).

Changing the code as follows makes it compile:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int aa[1][10] = { { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };

int f(int arr[1][10])
{
  int s = 0;
  for (auto i : arr[0])
    s += i;
  return s;
}

int main()
{
  return f(aa);
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Comment 1 Jonathan Wakely 2012-08-17 15:40:42 UTC
I think the compiler's correct to reject the first example, the type of arr is int* so it's not an array, and so the for loop calls begin(arr) and end(arr)

In the second example the parameter type is int(*)[10] so arr[0] is an array of known bound, and so the for loop works.
Comment 2 Jonathan Wakely 2012-08-17 15:43:02 UTC
It would be nice if G++ told you the type of the range, as Clang++ does:

a.cc:9:15: error: use of undeclared identifier 'begin'
  for (auto i : arr)
              ^
a.cc:9:15: note: range has type 'int *'