This question already has answers here:
Closed 7 years ago.
In this piece of code, why f() is declared as "double & f(..."? What does it mean and how does it work? I don't even know what to google to find the answer to my question. Please help.
double a = 1, b = 2;
double & f (double & d) {
d = 4;
return b;
}
I know ampersand sign means the address of a variable or a function, but I don't see why it would make sense to write it when you are declaring a function.
When the &
operator is used in a declaration form, preceded by a type it doesn't mean "the address of" but a "reference to" which is essentially an automatically dereferenced pointer with disabled pointer arithmetic.
There are no references in C, so if you want to pass or return by reference, you had to pass a const pointer and dereference it to access the pointed to value. C++ added references to make this concept easier, to prevent accidental walking off the address with pointer arithmetic, and to save the need to dereference the pointer. This makes working with it much easier and resulting in cleaner and more readable syntax.
Consider these two functions: power2()
and add()
:
void power2 (double& res, double x) {
res = x * x;
}
double& add (double& x) {
return ++x;
}
The first computes the power of x
and stores the result in the first argument, res
, – it does not need to return it.
The second returns a reference, which means this reference can later be assigned a new value.
Example:
double res = 0;
power2(res, 5);
printf("%f\n", res);
printf("%f\n", ++add(res));
Output:
25.000000
27.000000
Please note that the second output is 27
, not 26 – it's because of the use of ++
inside the printf()
call.
In this case, the ampersand does not mean taking an address, but it denotes a reference. Here, f
is a function that takes a reference to double as parameter and returns a reference to double.
You might want to read about C++'s references in your textbook of choice, since they are a very basic part of the language.