Search code examples
c++constantspass-by-reference

Why a const variable cannot be passed by reference?


My lecture notes said

The argument to a reference parameter must be a variable, not a constant or an expression.

And thus

int f(double & var); // function prototype
...
const double t = 4.0;
int ret = f(t); 

f(t) is illegal.

But I do not understand, why would t be illegal. t is a constant, but still a variable, and I don't think there's anything wrong passing t by reference.


Solution

  • What if the function f modifies var? That shouldn't happen if t is const.

    Here's an example implementation of f:

    int f(double & var)
    {
        var += 1;
        return var;
    }
    

    This will change whatever is passed as an argument. But if the argument was const... tough luck. Then it's not allowed and the compiler explicitly tells you this.

    This is the error generated by the compiler:

    error: binding reference of type 'double&' to 'const double' discards qualifiers
    

    So by passing a const variable into the function (without a non-const argument), you're telling the compiler to neglecting the constness of the variable in the first place.

    If you wish to pass it by reference, pass it by const-reference:

    int f(const double & var)  //  or int f(double const& var)
    {
        var += 1;
        return var;
    }
    

    This tells the compiler to retain the const-ness of its arguments.