holotko wrote:
> 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?
This approach does use pointers. It just hides the fact that pointers
are being used.
> Also, this ONLY seems to work under C++, it does not work in C.
Correct.
> Using pointers works in both C & C++. Was this implemented in C++ as
> a means of getting around the need to use pointers?
It is syntactic sugar. The calling function will pass a pointer to the
variable, and the calling function will dereference that pointer.
Personally, I consider this feature (like many of C++'s features) to
be a bad idea. If you are reading some code, and come across:
somefunction(somevariable);
there is no way to tell whether somevariable will be modified without
looking at the prototype for somefunction. With C, you can be sure that
somefunction(somevariable);
doesn't modify somevariable, whereas
somefunction(&somevariable);
might modify somevariable.
> 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;
> }
Yep. And if you compare the code which is generated, it will be
identical to using a reference.
--
Glynn Clements <[EMAIL PROTECTED]>