String literals

suggest change

An ordinary string literal is a null-terminated array of char with static storage duration. Because that array outlives the function, returning a pointer to the literal is defined:

const char *get_hello(void) {
    return "Hello, World!";  /* safe */
}

For historical reasons, the elements are not const. Modifying them is still undefined behavior. A program that does so may crash, but that is not required.

char *foo = "hello";
foo[0] = 'y';  /* Undefined behavior - BAD! */

Where a pointer points to a string literal – or where it sometimes may do – it is advisable to declare that pointer’s referent const to avoid engaging such undefined behavior accidentally.

const char *foo = "hello";
/* GOOD: can't modify the string pointed to by foo */

On the other hand, a pointer to or into the underlying array of a string literal is not itself inherently special; its value can freely be modified to point to something else:

char *foo = "hello";
foo = "World!"; /* OK - we're just changing what foo points to */

Furthermore, although initializers for char arrays can have the same form as string literals, use of such an initializer does not confer the characteristics of a string literal on the initialized array. The initializer simply designates the length and initial contents of the array. In particular, the elements are modifiable if not explicitly declared const:

char foo[] = "hello";
foo[0] = 'y';  /* OK! */

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents