5

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?

Arin Chaudhuri
  • 382
  • 4
  • 14
  • @nm that thread is tagged C++ (the answer is different in C, sadly, although some of the answers on that thread do addres it) – M.M Feb 02 '15 at 21:24

1 Answers1

6

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.

Community
  • 1
  • 1
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158