I saw something the other day which, after all the years I have been
working with C. I had never seen before, (or at least never paid much
attention to). The idea involved passing arguments to functions by
reference, so that a reference to the variable/argument is passed to
the function and thus, as a side effect the function can modify the
value at that reference. I had ALWAYS done this (or at least simulated
this) by using pointers, but the other day I saw it done without
pointers as follows:
#include <iostream.h>
void changetemp( float& );
int main()
{
float temp = 25;
cout << "temp is: " << temp << " deg F \n";
changetemp(temp);
cout << "temp is now: " << temp << "deg F \n");
exit(0);
}
void changetemp( float& tmp )
{
tmp += 5;
}
Is there any advantage to this approach over using pointers? Also,
this ONLY seems to work under C++, it does not work in C. Using
pointers works in both C & C++. Was this implemented in C++ as a means
of getting around the need to use pointers? Pardon my ignorance but I
am still in the learning stages with respect to C++.
Normally I would accomplish the same thing via pointers, like so:
changetemp( & temp ); // pass the adress of the value to function.
void changetemp( float *tmp )
{
*tmp += 5;
}
Sincerely,
/John <[EMAIL PROTECTED]>
Programmer, Consultant, Administrator, and Professional Lunatic.