Passing an array by reference

后端 未结 5 1189
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 11:52

How does passing a statically allocated array by reference work?

void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 12:34

    It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

    E.g. int &myArray[100] // array of references

    So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

    E.g int (&myArray)[100] // reference of an array of 100 ints

提交回复
热议问题