I understand C++ passes arrays by reference even if we don't use the reference operator (&), but since it can be added with no harm (I think), I'm curious as to why this code throws
declaration of 'matrix' as array of references
void function (int &matrix[2][5]) {
//something
}
int main() {
int matrix[2][3] = {{1,2,3}, {4,5,6}};
function(matrix);
}
while adding parentheses in (&matrix)
works:
void function (int (&matrix)[2][5]) {
//something
}
&matrix[2][5]
has a different meaning from (&matrix)[2][5])
.
The former means matrix
is a two dimensional array of references to int and the latter means matrix
is a reference to a two dimensional array of integers .
Since matrix
is defined as a two dimensional array in main
, the second form succeeds.
The cdecl tool can be helpful here:
int (&matrix)[2][5] - declare matrix as reference to array 2 of array 5 of int
int &matrix[2][5] - declare matrix as array 2 of array 5 of reference to int
I understand C++ passes arrays by reference even if we don't use the reference operator (&)
This is incorrect. C++ doesn't pass arrays as references. Additionally, there is no such thing as a "reference operator".
I'm curious as to why this code throws
The code is not "throwing", that term is used in the context of exceptions. You are simply getting a compilation error, as you're attempting to define an array of references to integers.
This happens because
int &matrix[2][5]
is grouped as
int &((matrix[2])[5])
by default. Adding parenthesis makes the compiler parse your type as "reference to an array of integers".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.