The text should say that a string literal has type “array of char
” and storage class static.
A string literal is text in C source code starting and ending with "
, such as "Hello, world."
(There are some embellishments to that form, not discussed in this answer.) A compiler builds the contents of that string literal into your program so that it exists in memory for the entire execution of the program. This is what we mean by static storage duration: It is static (unchanging) throughout the program. In contrast, variables declared inside functions, particularly inside blocks, are given memory only during execution of the block they are in, and objects given memory by malloc
have that memory only until free
is called (or certain related routines).
Kernighan and Ritchie should not have used “string” in this sentence instead of “string literal.” In C terminology, a string is any sequence of characters terminated by a null character (and not containing any earlier null characters). You can have a string in any memory, whether it is static, thread, automatic, or dynamically allocated.
Also, technically, a string literal is the source code that starts with "
and ends with "
. The array that results from it is a different thing. However, people often use the term “string literal” loosely to refer to that array.