3

Possible Duplicate:
Implicit cast from char** to const char**

Given the following code:

void foo( const char ** buffer );

void bar() 
{
    char * buffer;
    foo( &buffer );
}

Why is it that if the foo() function has a const char * parameter the compiler doesn't complain when passing in a char * variable into it? But when using char **, it cannot convert it to const char **? Does the compiler add any const qualifiers in the former case?

I've read section 4.4 of the C++ standard and it just confused me further.

Community
  • 1
  • 1
MarkP
  • 4,168
  • 10
  • 43
  • 84

3 Answers3

5

Yes, you cannot implicitly convert from a T ** to a const T **, because the compiler can no longer guarantee that the const-ness won't be violated.

Consider the following code (borrowed from the C FAQ question on exactly this topic: Why can't I pass a char ** to a function which expects a const char **?):

const char c = 'x';
char *p1;
const char **p2 = &p1;  // 3
*p2 = &c;
*p1 = 'X';              // 5

If the compiler allowed line 3, then line 5 would end up writing to a const object.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 2
    How would you modify the above code to compile properly? – MarkP Apr 30 '12 at 13:02
  • 1
    @MarkP, `foo( const_cast(&buffer) );` should work. And it's strange as for me, but standard allows `const_cast` to convert between types with different cv-qualification in any direction. So you can either remove `const` qualification by it or add, if you want. – 23W May 08 '18 at 10:55
2

Consider:

char const someText[] = "abcd";

void
foo( char const** buffer )
{
    *buffer = someText;
}

void
bar()
{
    char* buffer;
    foo( &buffer );
    *buffer = 'x';
}

If this were legal, it would be possible to modify a const object without an intervening const_cast. The conversion is forbidden because it violates const-ness.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
1

You are probably confusing the level of indirection the const applies to.

A char** can be described as pointer to a pointer to a character whereas a const char** can be described as pointer to a pointer to a constant character.

So when we write this differently, we have pointer to A (where A = pointer to character) and we have pointer to B (where B = pointer to a constant character).

Clearly now (I hope) A and B are distinct types, as such a pointer to A can not be assigned toa a pointer to B (and vice versa).

PlasmaHH
  • 15,673
  • 5
  • 44
  • 57