-1

I have following code:-

static char* ListOfStr[] = { "str1", "str2", "str3" };
void Foo(const char** listOfStr)
{
// do something
}

When I call Foo like;

Foo(ListOfStr);

I get Error Can not convert char** to const char** (C2664 - vc++)

I know how to solve the problem using casting or other way around like defining const array at first place.

But isn't it safe to use char** as const char** than why it gives error ? I supposed there should be auto convertion like std::string to const std::string when passing to function. Only the reverse of this cont char** to char** must give the Error without cast.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
vkchavda
  • 93
  • 5

1 Answers1

2

The issue is covered in the C++ FAQ, thanks to Steve Summit: https://isocpp.org/wiki/faq/const-correctness#constptrptr-conversion

I have looked at it for 10 minutes and still don't fully understand it, but the problem is apparently that you could create non-const aliases and thus modify an originally const object if this were allowed.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
  • At the end, if every step was legal, q would point to p and p would point to x, with q and x being const, but not p, which is a problem. q was basically used in order to make p point to x within `*q = &x; ` (with *q being p at that moment). Thus, one step must be forbidden. All lines except the one in the middle are something done commonly. I think if I hadn't read your link, I'd never guessed that this harmless looking line is actually dangerous in a hundred years. – Aziuth Dec 04 '21 at 20:16
  • @Aziuth q is not const either... it points to pointers to const. – Peter - Reinstate Monica Dec 04 '21 at 20:24