Arrays of References in C : Explained with Standard Reference
Consider the following code:
int a = 1, b = 2, c = 3; int& arr[] = {a,b,c,8};
This code doesn't compile. Why? Let's explore the C standard to find the answer.
C Standard Guidance
According to the C Standard §8.3.2/4:
"There shall be no references to references, no arrays of references, and no pointers to references."
Reasoning behind the Restriction
This restriction is in place because references are not objects in the traditional sense. They are essentially aliases to objects and do not occupy memory, therefore they do not have addresses. Consequently, declaring an array of references makes little sense since there is no array of objects to refer to.
Alternative Approach
If you need to simulate an array of references, you can create a class that encapsulates a reference, as shown in the following example:
struct cintref { cintref(const int & ref) : ref(ref) {} operator const int &() { return ref; } private: const int & ref; void operator=(const cintref &); }; int main() { int a=1,b=2,c=3; cintref arr[] = {a,b,c,8}; }
This approach essentially simulates an array of references by creating an array of objects of the cintref class. Each object holds a reference to the corresponding integer variable.
The above is the detailed content of Why Can't You Declare an Array of References in C ?. For more information, please follow other related articles on the PHP Chinese website!