A C string literal represents an array object of type char[len+1]
, where len
is the length, plus 1 for the terminating '\0'
. This array object has static storage duration, meaning that it exists for the entire execution of the program. This applies regardless of where the string literal appears.
The literal itself is an expression type char[len+1]
. (In most but not all contexts, it will be implicitly converted to a char*
value pointing to the first character.)
Compilers may optimize this by, for example, storing identical string literals just once, or by not storing them at all if they're never referenced.
If you write this:
const char *s="Hello World\n";
inside a function, the literal's meaning is as I described above. The pointer object s
is initialized to point to the first character of the array object.
For historical reasons, string literals are not const
in C, but attempting to modify the corresponding array object has undefined behavior. Declaring the pointer const
, as you've done here, is not required, but it's an excellent idea.