4

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Vishal
  • 3,178
  • 2
  • 34
  • 47

2 Answers2

12

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;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Thanks. This works. But how could I have known that a bracket is to be placed around `(&e)` ? – Vishal Jul 16 '18 at 09:28
  • @vishal Remember it. :) Well, if you write something like `int a[100];`, `a` will be considered as an array of 100 `int`s. If you write `int& a[100];`, `a` will be an array of 100 `int&`s (thus it's ill-formed). So you have to use parentheses to tell that it's not array, but a reference to array. It's same as pointer to array. e.g. if you want a pointer to array of 100 `int`s you have to write `int (*a)[100];`. BTW: Function pointers have similar issues. – songyuanyao Jul 16 '18 at 09:33
  • 1
    @vishal : keep in mind that C types are [read from the inside out in a clockwise spiral](https://stackoverflow.com/questions/89056/how-do-you-read-c-declarations) : `e` is a reference (`&`) to and array of 100 (`[100]`) `int`s. – Sander De Dycker Jul 16 '18 at 09:37
0

If you want to avoid this kind of confusion, it is actually a good opportunity to move to templated types, as there is std::array. Among other things, they provide the means to somewhat unify the syntaxes you need to use, and as in this example, remove the confusion of references/arrays/...

int main() 
{
    std::array<int, 100> a;
    std::array<int, 100>& e = a;
}

Nothing prevents you from still providing a type alias:

using array_type = std::array<int, 100>;
rubenvb
  • 74,642
  • 33
  • 187
  • 332