Marking a location as const
is a sort of “downgrade”: everything can become const
but the other way around cannot happen. So if I pass a non-const
string to a function that requires a const
string no problem, but if I do the opposite the compiler will warn me.
Hence this code works fine:
#include <stdio.h>
void print_constant_string (const char * const str) {
printf("%s\n", str);
}
int main () {
char * my_string = "Hello world!";
print_constant_string(my_string);
return 0;
}
What I never understood is why this code instead gives me a warning (“warning: passing argument 1 of ‘print_array_of_constant_strings’ from incompatible pointer type [-Wincompatible-pointer-types]”):
#include <stdio.h>
void print_array_of_constant_strings (const char * const * const strarr) {
for (size_t i = 0; strarr[i]; printf("%s\n", strarr[i++]));
}
int main () {
char ** my_array = (char * []) { "foo", "bar", NULL };
print_array_of_constant_strings(my_array);
return 0;
}
Am I not “downgrading” my variable exactly as I did before? What could possibly go wrong if the compiler did not warn me?