Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an argument of type double ** incompatible with a parameter of type const double ** [duplicate]

Tags:

c

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?

like image 368
Arin Chaudhuri Avatar asked Feb 02 '15 20:02

Arin Chaudhuri


1 Answers

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.

like image 85
Mooing Duck Avatar answered Oct 07 '22 08:10

Mooing Duck