Bad call with const signature in C

Possible duplicate:
Why is it not legal to convert (pointer to pointer to non-constant) to (pointer to pointer to constant)

Why am I getting a warning (gcc 42.2) with the following call to foo?

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

I understand why we cannot call a function, except char ** with const char ** , but it seems to me the other way around, so why the following warning?

 warning: passing argument 1 of 'foo' from incompatible pointer type 
+6
source share
1 answer

It is not right. There is no real opportunity to argue with the compiler, since it is supported by the specification. Here is an example that explains why this is wrong:

 void func(const char **p) { *p = "abc"; } void func2(void) { char *a; func(&a); *a = 'x'; } 

If the compiler did not spit out the error, your program will probably crash because you will rewrite the string literal (which is often marked as read-only in memory).

Thus, you cannot implicitly cast char ** to const char ** , because it will allow you to remove the const qualifier from any value - basically, it will allow you to ignore const as desired without an explicit cast.

The main reason the compiler gives a warning instead of an error is because a lot of old code does not use the const qualifier, wherever it would be if the code was written today.

+8
source

All Articles