Why is the following program giving an error?

Why does the following program give a warning?

Note . Obviously, sending a normal pointer to a function that requires a 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'
+3
source share
1 answer

This code violates the correct const.

The problem is that this code is fundamentally unsafe because you can inadvertently modify the const object. The C ++ FAQ Lite has a great example of this in the answer "Why am I getting an error message that converts 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!!
   ...
 }

( Marshall Cline ++ FAQ Lite document, www.parashift.com/c++-faq-lite/)

const-qualifying :

void sam(char const* const* p) { }
+10

Source: https://habr.com/ru/post/1758109/


All Articles