Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help decoding this typedef

I'm trying to create a reference to an array.
It works this way:

typedef int array_type[100];

int main() {
    int a[100];
    array_type &e = a;    // This works
}

But then I was trying to remove the typedef, and get the same thing working. Haven't been successful.

int main() {
    int a[100];
    // int[100] &e = a;    // (1) -> error: brackets are not allowed here; to declare an array, place the brackets after the name
    // int &e[100] = a;    // (2) -> error: 'e' declared as array of references of type 'int &'
}

What is wrong with my interpreation of typedef? And how could I remove the typedef, and still get the same functionality.

like image 353
Vishal Avatar asked Dec 13 '22 15:12

Vishal


1 Answers

You need to add parentheses to tell that this is a reference to array, but not an array of something. e.g.

int (&e)[100] = a;

Or use auto or decltype (both since C++11) to make it simpler.

auto& e = a;
decltype(a)& e = a;
like image 118
songyuanyao Avatar answered Dec 26 '22 00:12

songyuanyao