Difference between `int* const& x` and `int* const x` in C++

Viewed 189

I've read of the differences between passing by value, passing by reference, and passing (a pointer) by constant reference, yet I'm don't understand the difference between the latter, and just passing a constant pointer. As an example, what is the difference between

int PI = 3;

int* getArg(int* const& x){
    x = Π
    return x;
}

int main() {

}

and

int PI = 3;

int* getArg(int* const x){
    x = Π
    return x;
}

int main() {

}

Both of these cause the same error: assignment of read-only parameter 'x'.

1 Answers

If you're clear on passing variables by value and by reference, then try breaking down complex types into parts to help make sense of what's going on:

using PointerToInt = int*;
using ConstPointerToInt = PointerToInt const;

int* getArg_v1(ConstPointerToInt x) {
    x = Π  // it's const by value so you're not allowed to change it
    return x;
}

int* getArg_v2(ConstPointerToInt& x) {
    x = Π  // it's const by reference so you're not allowed to change it
    return x;
}
Related