views:

144

answers:

1

Why does the following program give a warning?

Note: Its obvious that sending a normal pointer to a function requiring const pointer does not give any warning.

#include <stdio.h>
void sam(const char **p) { }
int main(int argc, char **argv)
{
    sam(argv);
    return 0;
}

I get the following error,

In function `int main(int, char **)':
passing `char **' as argument 1 of `sam(const char **)' 
adds cv-quals without intervening `const'
+11  A: 

This code violates const correctness.

The issue is that this code is fundamentally unsafe because you could inadvertently modify a const object. The C++ FAQ Lite has an excellent example of this in the answer to "Why am I getting an error converting a Foo**Foo const**?"

class Foo {
 public:
   void modify();  // make some modify to the this object
 };

 int main()
 {
   const Foo x;
   Foo* p;
   Foo const** q = &p;  // q now points to p; this is (fortunately!) an error
   *q = &x;             // p now points to x
   p->modify();         // Ouch: modifies a const Foo!!
   ...
 }

(Example from Marshall Cline's C++ FAQ Lite document, www.parashift.com/c++-faq-lite/)

You can fix the problem by const-qualifying both levels of indirection:

void sam(char const* const* p) { }
James McNellis