Home > Backend Development > C++ > Why Are Arrays of References Prohibited in C ?

Why Are Arrays of References Prohibited in C ?

Patricia Arquette
Release: 2024-12-05 14:21:10
Original
430 people have browsed it

Why Are Arrays of References Prohibited in C  ?

Arrays of References and the C Standard

In C , an attempt to declare an array of references, as in the following code snippet, will result in a compilation error:

int a = 1, b = 2, c = 3;
int& arr[] = {a,b,c,8};
Copy after login

This is explicitly prohibited by the C Standard, which states in §8.3.2/4 that "There shall be no references to references, no arrays of references, and no pointers to references."

Why Are Arrays of References Illegal?

The reason for this prohibition lies in the nature of references. Unlike objects, which occupy memory and have an address, references are aliases for other objects. They do not have an independent existence and do not occupy memory themselves.

An array of references, therefore, would be an array of pointers to objects, which could lead to confusion and potential memory management issues. For example, if the object pointed to by a reference were to be deleted, the reference would become dangling and the array could contain invalid data.

Simulating Arrays of References

While creating true arrays of references is not allowed in C , there are ways to simulate their behavior using other techniques. One common approach is to use a class that contains a reference member variable, as shown in the following code:

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 allows us to create an array of objects that each contain a reference to an integer variable. However, it's important to note that this is not a true array of references but rather an array of objects that store references.

The above is the detailed content of Why Are Arrays of References Prohibited 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template