0

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.

8
  • Why would you want to pass an array by reference? Commented Jan 6, 2014 at 18:22
  • @Cornstalks Why wouldn't you want to pass an array by reference? @burakim: Since you've tagged this C++11, you could switch to std::array<int, 3> and avoid such vagaries of C declarator syntax. Commented Jan 6, 2014 at 18:31
  • 1
    @Praetorian: because arrays can't be assigned to, and already decay to pointers. Commented Jan 6, 2014 at 18:57
  • @Cornstalks I don't see how not being assignable is relevant, you can still assign to individual elements. And the decaying to pointer loses size information, which makes it inconvenient for most use cases. Commented Jan 6, 2014 at 19:01
  • By passing by reference, you may use std::end(testarray) Commented Jan 6, 2014 at 19:04

2 Answers 2

7

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.