?
=?ISO-8859-1?Q?Ney_Andr=E9_de_Mello_Zunino?=
Hello.
I have a question regarding arrays when used as arguments in function
calls. In a situation like the following:
void foo(int array[2])
{
// ...
}
int bar[2] = {2, 3};
foo(bar);
What happens to the 'bar' "object" being passed to the function? I
expected it to be passed as it is, i.e., an "object" of type int [2],
without any conversion taking place. However, section 7.2.1 of
Stroustrup's TCPL 3rd Edition reads:
"If an array is used as a function argument, a pointer to its initial
element is passed."
and a bit further:
"...arrays differ from other types in that an array is not (and cannot
be) passed by value."
Does it mean that, in the sample code above, 'bar' is actually being
passed as 'int*' and then converted back to int [2] in the called
function? I am aware that the name of arrays may be used as pointers to
its first elements and that this conversion takes place automatically,
but I thought that might be different when explicitly declaring an
argument as having a type such as int [2].
Why can't arrays be passed by value? I find it somewhat inconsistent
once one could easily imply reference semantics by using pointer or
reference syntax:
void foo(int (*array)[2]) {}
void foo(int (&array)[2]) {}
I would appreciate if these issues could be elaborated a little so that
I can clear up my concepts.
Thank you,
I have a question regarding arrays when used as arguments in function
calls. In a situation like the following:
void foo(int array[2])
{
// ...
}
int bar[2] = {2, 3};
foo(bar);
What happens to the 'bar' "object" being passed to the function? I
expected it to be passed as it is, i.e., an "object" of type int [2],
without any conversion taking place. However, section 7.2.1 of
Stroustrup's TCPL 3rd Edition reads:
"If an array is used as a function argument, a pointer to its initial
element is passed."
and a bit further:
"...arrays differ from other types in that an array is not (and cannot
be) passed by value."
Does it mean that, in the sample code above, 'bar' is actually being
passed as 'int*' and then converted back to int [2] in the called
function? I am aware that the name of arrays may be used as pointers to
its first elements and that this conversion takes place automatically,
but I thought that might be different when explicitly declaring an
argument as having a type such as int [2].
Why can't arrays be passed by value? I find it somewhat inconsistent
once one could easily imply reference semantics by using pointer or
reference syntax:
void foo(int (*array)[2]) {}
void foo(int (&array)[2]) {}
I would appreciate if these issues could be elaborated a little so that
I can clear up my concepts.
Thank you,