Question

I have a question about passing array with reference operator. I want to write code that pass array using reference operator. Then I tried

void swap(int &testarray[3]){
 // code
}

It gives me error. It says,

/main.cpp:5: error: declaration of 'testarray' as array of references

However when changed my code with

void swap(int (&testarray)[3]){
  // code
  }

It runs properly. Only difference is having bracket.

Why it needs bracket and what is the difference between int (&testarray)[3] and int &testarray[3]

Thanks for helping.

Was it helpful?

Solution

void foo(int &testarray[3]) is interpreted as void foo((int &)testarray[3]) due to priority. And array of references are illegal.

Whereas void foo(int (&testarray)[3]) is interpreted as you want. (reference of an array of 3 int).

void foo(int testarray[3]) is equivalent to void foo(int testarray[]) which decays to void foo(int *testarray). (int pointer).

OTHER TIPS

In fact this construction

int & testarray[3]

defines an array of references to integral objects. The C++ Standard does not allow to define arrays of references to objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top