Home > Software design >  difference between double and double& in c
difference between double and double& in c

Time:09-17

I have the following function to calculate the mean of a double[] in c :

double& Vector::mean() {
    double sum = 0.0;
    for (int i = 0; i < size; i  ) {
        sum  = *(arr   i);
    }
    double m = sum / size;
    return m;
}

this compiles and runs, but this doesn't:

double& Vector::mean() {
    double sum = 0.0;
    for (int i = 0; i < size; i  ) {
        sum  = *(arr   i);
    }
    return (sum / size);
}

With the following error:

Non-const lvalue reference to type 'double' cannot bind to a temporary of type 'double'

This is implemented in a class where arr is of type double*.

What is the difference between simply returning sum / size and returning a variable double m = sum / size? I have a vague idea that the reason has something to do with the difference between types double and double& but, but wouldn't returning m be the same as returning a calculated double value? Any help is appreciated.

CodePudding user response:

Using double& indicates that you are returning by reference. This means that rather than directly returning a value, the function returns a memory location where the value is stored, which is immediately dereferenced and converted to a value in the calling code in most cases. Since sum/size is an expression and not a variable, an address cannot be identified and the compiler throws an error. However, m is a variable and has an address that can be returned. However, in this case m falls out of scope immediately when the member function exits, so this also should not be done. In this case it would probably be more appropriate to returndouble, which returns a value directly to the calling code.

  • Related