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
Yes. const is there in C, from C89.
The const keyword allows a programmer to tell the compiler that a particular variable should not be modified after the initial assignment in its declaration.
A function declaration tells the compiler the function's signature and return type. In the above example, the function's signature is F(int) . The constness of the function's parameter type is ignored, so both declarations are equivalent (See “Overloadable declarations”.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With