I know implicit conversion from char **
to const char **
cannot be done and why, and that the conversion to char *const *
works. See bottom for links to explanation on that.
It all makes sense apart from one particular thing. So I have the following code:
#include <stdio.h>
void
print(const char *const*param)
{
printf("%s\n", param[0]);
}
int
main(int argc, char **argv)
{
print(argv);
return 0;
}
If I compile this as a C++ code, it compiles quite fine. However, if the same code is compiled as a C code only, I get an error (well, a warning, but let's suppose -Werror
, i.e. treat warnings as errors).
gcc:
test.c: In function ‘main’:
test.c:12:11: warning: passing argument 1 of ‘print’ from incompatible pointer type [-Wincompatible-pointer-types]
print(argv);
^
test.c:4:1: note: expected ‘const char * const*’ but argument is of type ‘char **’
print(const char *const*param)
^
clang:
test.c:12:11: warning: passing 'char **' to parameter of type 'const char *const *' discards qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers]
print(argv);
^~~~
test.c:4:25: note: passing argument to parameter 'param' here
print(const char *const*param)
^
Both behaviours are standard-independent and also compiler-independent. I tried various standards with both gcc
and clang
.
There are two reasons for this inquiry. Firstly, I want to understand whether there is a difference and, secondly, I have a function that does nothing with any layer of the pointers and I need it to be able to work with const char **
as well as char *const *
and char **
. Explicitly casting each call is not maintainable. And I have no idea how should the function prototype look like.
This is the question that started my curiosity: Implicit conversion from char** to const char**
And here is another nice explanation for the char ** => const char**
problem:
http://c-faq.com/ansi/constmismatch.html
If the links are confusing related to this question, feel free to edit them out.