1

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?

  • 1
    *"What could possibly go wrong"* Nothing. C++ allows this (unlike C), so presumably this is a small defect in the C spec. – HolyBlackCat Oct 31 '20 at 15:50
  • 1
    g++ complains as well: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings] – Rachid K. Oct 31 '20 at 15:57
  • @RachidK. Yes, but this is an unrelated issue. (String literals having type `char[N]` in C, but `const char[N]` in C++.) – HolyBlackCat Oct 31 '20 at 16:03

0 Answers0