Re: Function arguments: References vs pointers
On Jun 17, 12:43 am, Rune Allnor <all...@tele.ntnu.no> wrote:
[snip]
One obvious difference is the calling syntax:
int k;
f(k);
g(&k);
The call to f() is "clean" from the programmer's point of view, it is
also transparent with respect to whether the function actually
uses call by reference or call by value. The call to g() is more
cumbersome; it may be very cumbersome if the argument is
not an individually declared variable but a member of some
struct or array.
Except for the source code being easier to read by the human
when using references, are there more differences between the
two forms?
Well, it might be easier to read, but harder to understand: it is not
clear from the `f(k)' line on it's own that `f()' ever going to modify
it's argument. You should name it appropriately (say, `get_xxx(int&)'
or something), or else it might take one to refer to manual in order
to understand what is going on in that call :-)
With the latter form `g(&k)' it is still not as obvious, but the
syntax gives one a hint...
Digging it deeper: probably you are asking this question because you
have a function which calculates _several_ values at once, otherwise
it suffices just to return the value. So, lets suppose you have
something like these alternatives:
void f(int& k, int& j);
void g(int* k, int* j);
You might consider then _returning_ the calculated values instead,
like this:
struct smth {
int k;
int j;
};
smth f();
....
smth val = f();
--
Regards,
Alex Shulgin
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]