Why are string literals const?

There are a couple of different reasons.

One is to allow storing string literals in read-only memory (as others have already mentioned).

Another is to allow merging of string literals. If one program uses the same string literal in several different places, it’s nice to allow (but not necessarily require) the compiler to merge them, so you get multiple pointers to the same memory, instead of each occupying a separate chunk of memory. This can also apply when two string literals aren’t necessarily identical, but do have the same ending:

char *foo = "long string";
char *bar = "string";

In a case like this, it’s possible for bar to be foo+5 (if I’d counted correctly).

In either of these cases, if you allow modifying a string literal, it could modify the other string literal that happens to have the same contents. At the same time, there’s honestly not a lot of point in mandating that either — it’s pretty uncommon to have enough string literals that you could overlap that most people probably want the compiler to run slower just to save (maybe) a few dozen bytes or so of memory.

By the time the first standard was written, there were already compilers that used all three of these techniques (and probably a few others besides). Since there was no way to describe one behavior you’d get from modifying a string literal, and nobody apparently thought it was an important capability to support, they did the obvious: said even attempting to do so led to undefined behavior.

Leave a Comment