Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array arguments by reference

I came across a function with this signature.

void foo(char (&x)[5])
{
}

This is the syntax for passing a fixed size char array by reference.

The fact that it requires parentheses around &x strikes me as unusual.

It is probably part of the C++03 standard.

What is this form called and can anyone point out a reference to the standard?

c++decl is not a friend yet:

$ c++decl 
Type `help' or `?' for help
c++decl> explain void foo(char (&x)[5])
syntax error
like image 605
Eddy Pronk Avatar asked Oct 26 '11 12:10

Eddy Pronk


2 Answers

There is nothing unusual or new about the syntax. You see it all the time in C with pointers. [] has higher precedence than &, so you need to put it in parentheses if you want to declare a reference to an array. The same thing happens with * (which has the same precedence as &): For example, to declare a pointer to an array of 5 chars in C, you would do char (*x)[5];. Similarly, a pointer to a function that takes and returns an int would be int (*x)(int); (() has same precedence as []). The story is the same with references, except that references are only on C++ and there are some restrictions to what types can be formed from references.

like image 163
newacct Avatar answered Oct 16 '22 21:10

newacct


There's nothing to explain, this is simply how the parsing rules for declarations work in C++:

char  & x[5] // declare x as array 5 of reference to char (not valid C++!)
char (&x)[5] // declare x as reference to array 5 of char

Caution: The first version is not valid C++, though, since you cannot have arrays of references. This is merely an explanation of the declaration syntax. (Sorry about taking so long to get this right, and thanks to the helpful comments!)

You're allowed to wrap the type identifier in arbitray levels of parentheses if you like, so you can also say char &(x)[5] (first case) or char (((&x)))[5] (second case).

like image 11
Kerrek SB Avatar answered Oct 16 '22 21:10

Kerrek SB