Waterscroll Waterscroll - 15 days ago 7x
C Question

Why gcc does not give a warning when you initialize an array without const with strings?

#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
a without warning.

When passing a
const char
to a function that receives a
, in other words, "casting" a
const char
, to a
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?


So why I don't get a warning in the first initialization?

Because the type of a string literal is array of char, not array of const char, notwithstanding the fact that modifying the elements of such an array produces undefined behavior. This comes down from the very first days of C, when there was no const. I'm sure its persistence into modern C revolves around the magnitude and scope of the incompatibility that would arise if the type were changed.

With respect to individual programs, however, GCC can help you out. If you turn on its -Wwrite-strings option then it will indeed give string literals type const char [length], with the result that a construct such as you presented will elicit a warning.