had I used that earlier I wouldn't have wasted time debugging |
Only if the values weren't being modified: obviously you couldn't use
const
if they are being changed. Another good reason to have function that does one thing only.
True but even this code (value vs ref) won't produce garbage values that the above code gives if there is no reference symbol. |
The
add_it_copy
doesn't change the values of
a
and
b
in
main
, and it returns a value. The calls to
add_it_copy
all produce the same answer, but the calls to
add_it_ref
produce different answers because
a
and
b
are changed by the function.
Btw, it could be a little confusing that you used
x
and
y
as parameters, because it is
a
and
b
that are being changed in
main()
This is borne out by the compile warnings:
In function 'int main()':
26:15: warning: unused variable 'x' [-Wunused-variable]
26:21: warning: unused variable 'y' [-Wunused-variable]
27:5: warning: unused variable 'total_1' [-Wunused-variable]
27:17: warning: unused variable 'total_2' [-Wunused-variable] |
I generally like to name the parameters the same as the arguments: it reinforces the idea that values are the same. Although they are only truly the same if passed by reference.
Also, with your function, delay the declaration of a variable until you have a sensible value to assign to it:
15 16 17 18 19 20 21 22
|
int add_it_ref(int &a, int &b)
{
int total(0);
a += b;
b += b;
int total = a + b;
return total;
}
|
Can I persuade you to not have
using namespace std;
?