How does ampersand in the return type of a function declaration work?

Azad Salahli picture Azad Salahli · Feb 27, 2013 · Viewed 19.4k times · Source

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.

Answer

kamituel picture kamituel · Feb 27, 2013

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.