What is useful about a reference-to-array parameter?

后端 未结 6 1478
野的像风
野的像风 2020-11-29 20:52

I recently found some code like this:

typedef int TenInts[10];
void foo(TenInts &arr);

What can you do in the body of foo()

6条回答
  •  醉酒成梦
    2020-11-29 21:10

    Shouldn't we also address the words in bold from the question:

    What can you do in the body of foo() that is useful, that you could not do if the declaration was void foo(int arr[]);?

    The answer is: nothing. Passing an argument by reference allows a function to change its value and pass back this change to the caller. However, it is not possible to change the value of the array as a whole, which would have been a reason to pass it by reference.

    void foo(int (&arr)[3]) { // reference to an array
       arr = {1, 2 ,3};       // ILLEGAL: array type int[3] is not assignable
       arr = new(int[3]);     // same issue
       arr = arr2;            // same issue, with arr2 global variable of type int[3] 
    }
    

提交回复
热议问题