Home > Backend Development > C++ > Why Can't You Declare an Array of References in C ?

Why Can't You Declare an Array of References in C ?

DDD
Release: 2024-12-04 17:10:13
Original
167 people have browsed it

Why Can't You Declare an Array of References in C  ?

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};
Copy after login

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};
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template