copx said:
I've noticed that it's valid to pass a string literal (like "test") to a
function that expects a const char *. Does this mean that in C a string
literal is automatically converted to a const char * if I pass it to a
function?
The function
void foo(const char *str)
may not modify the string pointed to be str. However it is legal to pass it
either a constant or a variable string. This makes sense. Say foo() prints
out the string on a teletype. Obviously we want to be able to print out
either constant strings or strings entered by the user or calculated at
runtime, however we wouldn't need to modify the string just to print it out.
Now consider the function bar
void bar(char *str)
{
str[0] = 'x';
}
This function modifies the input, so it cannot be const.
const char *string = "Hello";
/* illegal */
bar(string);
char string[32] = "Hello";
/* legal */
bar(string);
/* legal but should not be legal */
bar("Hello");
The compiler will allow you to pass the string literal "Hello" to bar(), but
you will then get undefined behaviour when you try to modify the string.
This is a quirk, and is for backwards compatibility. Originally there was no
"const" keyword in C, and enforicing the rule that string literals are const
qualified would have meant breaking a lot of existing and otherwise
perfectly good code.