Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is impossible to create an array of references in c++?

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}; 
like image 575
Mihran Hovsepyan Avatar asked Mar 28 '11 14:03

Mihran Hovsepyan


People also ask

Why is it not possible to declare an array of reference?

An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.

Why are arrays always passed by reference in C?

The only reason for passing an array explicitly by reference is so that you can change the pointer to point to a different array. If a function only looks at the contents of an array, and does not change what is in the array, you usually indicates that by adding const to the parameter.

What is array in C How can you reference it?

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To create an array, define the data type (like int ) and specify the name of the array followed by square brackets [].

Can we create reference to reference in C++?

// values as they all refer to the same variable. 1) Once a reference is created, it cannot be later made to reference another object; it cannot be reset.


1 Answers

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.

like image 172
James Kanze Avatar answered Oct 11 '22 10:10

James Kanze