2

I have a code which does more or less:

bar(const char**)
{
// stuff
}

foo(char** arr)
{
  bar(arr);
}

The compiler notifies me that i am doing an invalid conversion from ‘char**’ to ‘const char**’. While I know what it means, I fail to understand why is it not allowed. It is perfectly ok to pass char* where const char* is needed.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • 1
    Don't you have an extra `*` in the function signature? – Andy Prowl Mar 29 '13 at 13:09
  • Do you mean... `bar(const char**)` ? – Suvarna Pattayil Mar 29 '13 at 13:10
  • I mean, in the function signature of `bar()` you have `const char***`, there's 3 asterisks. Didn't you mean to have two perhaps? – Andy Prowl Mar 29 '13 at 13:10
  • 1
    It's nothing to do with the `const`, it's the extra `*` as Andy Prowl suggested. – Jonathan Potter Mar 29 '13 at 13:11
  • @SuvP: Yes, that's what I meant – Andy Prowl Mar 29 '13 at 13:11
  • Yeah, the signature was wrong, sorry :( – Dariusz Mar 29 '13 at 13:13
  • 1
    One of the many duplicates. See [comp.lang.c FAQ list · Question 11.10 - Why can't I pass a char ** to a function which expects a const char **?](http://c-faq.com/ansi/constmismatch.html). – Alexey Frunze Mar 29 '13 at 13:15
  • While I agree that the problem is the same as in the submitted duplicate, I would suggest leaving the question and posting an answer. I did not manage to find the resolution to my problem in google and I believe that the question can help other people – Dariusz Mar 29 '13 at 13:19
  • @PeteBecker you edited the question - but the original was better. Not only can't you implicitly convert char** to const char**, you can't do it explicitly in C++. Please revert. – Dariusz Mar 29 '13 at 14:16
  • @Dariusz - you can force the conversion with a `const_cast`. – Pete Becker Mar 29 '13 at 14:25
  • @Dariusz: well you can do it explicitly (e.g. `const_cast`), and Pete knows a bit about what you can do, being the one who penned the current standard. u now. so -- i was too tired to notice when i edited the title, but Pete fixed it. – Cheers and hth. - Alf Mar 29 '13 at 14:25

2 Answers2

1

because if it was allowed then you could inadvertently change something that was declared const.

here's a concrete abuse example, if the rules allowed this:

char const* s = "a literal, very const";

bar(const char** pp )
{
    *pp = s;
}

foo(char** arr)
{
  bar(arr);
  char* unconsted_s = *arr;
  unconsted_s[0] = 'X';
}

This is also a FAQ. It’s often a good idea to check the FAQ (or just google) before asking.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
0

It can lead to similar scenario if its allowed.

void foo(int** arr)
{
    /*Can freely modify value at location pointed by a*/
   **arr = 6;
}


int main()
{
 /*Pointer to constant*/
 int i = 5;

 const int* a =&a;

 /*Not a pointer to constant*/
 int** aa= &a;

 foo(aa);

return 0;
}
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59