I get a message about passing an incompatible pointer type from gcc when I pass a double ** to a function that expects a const double **. This is confusing to me since const double ** just puts more constraints on the use of the parameter passed in. How is this essentially different from passing a double * to a function that expects a const double *?
Added later: Passing double ** to a function that expects const double * const * is similarly problematic, any idea what can go wrong for this?
If you pass a pointer to a const T
by value, the function cannot edit the caller's pointer, nor the T
, so all is safe.
If you pass a pointer to a pointer to a const T
by value, the function can't edit the T
, but it can edit the second pointer. And since the pointee types are different (const vs mutable), that can wreck havoc.
static const double PI = 3.14;
void function(const double** p) {
*p = Π //point at the const double PI
}
int main() {
double* p;
function(&p); //pass pointer to pointer to double
*p = -1; //changing a static const global! That's bad!
}
Matt McNabb observes that if the parameter was const double*const*
then C++ would allow it, thought C doesn't, probably due to simple oversight.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With