6

Possible Duplicate:
why isnt it legal to convert (pointer to pointer to non-const) to a (pointer to pointer to a const)

Why do I get a warning (gcc 42.2) with the following call of foo?

void foo(const char **str)
{
  (*str)++;  
}

(...)
char **str;
foo(str);
(...)

I understand why we cannot call a function that excepting a char ** with a const char **, but the opposite seems ok to me, so why the following warning?

warning: passing argument 1 of 'foo' from incompatible pointer type
Community
  • 1
  • 1
Guid
  • 2,137
  • 2
  • 20
  • 33

1 Answers1

8

It is wrong. There is no real room for arguing with the compiler here, since it's supported by the spec. Here's an example which explains exactly why it is wrong:

void func(const char **p)
{
    *p = "abc";
}

void func2(void)
{
    char *a;
    func(&a);
    *a = 'x';
}

If the compiler didn't spit out an error, your program would probably crash because you'd be overwriting a string literal (which is often marked read-only in memory).

So you cannot implicitly cast char ** to const char ** because it would allow you to remove the const qualifier from any value — basically, it would allow you to ignore const at will without an explicit cast.

The main reason the compiler gives a warning instead of an error is because lots of old code does not use the const qualifier where it would if the code were written today.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415