29

C++ Standard 8.3.2/4 says:

There shall be no references to references, no arrays of references, and no pointers to references.

But I can't understand why this restriction is added to c++. In my opinion the code bellow can easily be compiled and work? What is the real cause of this restriction?

int a = 10, b = 20;
int &c[] = {a, b};
Mihran Hovsepyan
  • 10,810
  • 14
  • 61
  • 111
  • Possible duplicate of [Why are arrays of references illegal?](https://stackoverflow.com/questions/1164266/why-are-arrays-of-references-illegal) – Michel Keijzers Jul 17 '19 at 19:39

4 Answers4

28

Because indexation into an array is actually defined in terms of an implicit conversion to a pointer, then pointer arithmetic. So to support this, you'd have to also support pointers to references, and define what pointer arithmetic means on them.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
5

Because references aren't objects. References were primarily introduced to support call by reference and return by reference without inserting & at call-site. What you probably want is an array of pointers.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
5

A reference cannot be reassigned, and has no size.

If arrays of references were allowed they would therefore have to be treated in a special way then.

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

This is what i read at:

5.2.1 Subscripting [expr.sub]

1 A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T and the other shall have enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type.61) The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ]

-C++ Draft.

int a = 10, b = 20;
int &c[] = {a, b};

So imagine &c[0] would be something like *&(c+0), IMHO references are like aliases. Hence going by the notion of arrays it would try to dereference the value held by the reference which one would not want.

Sadique
  • 22,572
  • 7
  • 65
  • 91