Why do we use `const` for strings when defining with pointers in C?

  • A+

I heard from a C developer that for defining arrays with pointers, we write
int *const a;
because arrays have variable values but constant pointers. But for strings, we write
const char *s;.

I didn't understand why. Is this correct? Do strings really have constant values and variable pointers in C?


Code such as int *const a; is nonsense in most use-cases. The main use of making a pointer const is when you have a pointer-based look-up table. Or when you want a pointer to be stored in read-only memory on an embedded system.

Some confused programmers like to write code like void func (int* const ptr) but this is only obfuscation, in my opinion, since ptr is a copy of the original pointer anyhow, and the caller couldn't care less what the function does with its local copy internally.

Not to be mixed up with const correctness, which means that pointers to read-only data should be declared as const int* ptr. This is widely recognized as good programming practice, and it is canonical C, since most of the C standard utilizes const correctness for the C standard library.

As for pointers to string literals (like "hello") specifically, they should be declared const char* ptr = "hello"; for the reason that modifying a string literal invokes undefined behavior. Meaning that modifying it is a bug and might cause a program crash. This is a known flaw in C - the type of the string literal itself, even though we aren't allowed to write to it, is char[]. This is for historical reasons. In C++ however, they have fixed this language flaw inherited from C, so all string literals are const char[] in C++.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: