#include <stdio.h>
void print(char *strings[]) {
while (*strings) printf("%s\n", *strings++);
}
int main(int argc, char *argv[]) {
char *array[] = {"Hello", "World", NULL}; // No warning?
const char *constArray[] = {"Hello", "World", NULL};
print(constArray); // Warning!
//constArray[0][0] = '!'; Compile time error
array[0][0] = '!'; // Run time error
return 0;
}
I was expecting to get a warning in char *array[] = {"Hello", "World", NULL}; because the characters of those strings are read only, but the compiler does not give me a warning about that. So basically the compiler is letting me "cast" a const char to a char a without warning.
When passing a const char to a function that receives a char in print(constArray);, in other words, "casting" a const char, to a char the compiler does give me a warning. I was expecting the compiler to give me a warning in both cases or in neither, but not in one case and not the other.
I think this warning is important to help prevent errors like in array[0][0] = '!';. So why I don't get a warning in the first initialization?
const char *cannot be assigned to an lvalue of typechar *-- it violates paragraph 6.5.16/1 of the standard. The issue here is in part that "read only" is a poor description of string literals, and that it is anyway not equivalent toconst. The standard does not say that string literals are read only; it says that attempting to modify their values produces undefined behavior. This is a fine but important distinction.