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'
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**?”(Example from Marshall Cline’s C++ FAQ Lite document, http://www.parashift.com/c++-faq-lite/)
You can fix the problem by const-qualifying both levels of indirection: