const with Pointers in C
const combines with pointers in three distinct ways, read right-to-left: const char *p is a pointer to const data (can't write through p, can repoint), char * const p is a const pointer to mutable data (can write, can't repoint), and const char * const p locks both. Mixing them up is the most common const bug in C.
String literals demand const char* (writing through them is undefined behavior), read-only function parameters take const pointers (letting callers pass const and non-const alike), and const-correct APIs document exactly what may change.
Read right-to-left
const char *p: pointer to const char. char * const p: const pointer to char. Position relative to * decides everything.
Literals need pointer-to-const
char *p = "hi"; warns (deprecated conversion) — const char *p = "hi"; is correct since literals are read-only.
Const params accept all
void f(const char *s) takes const and non-const arguments alike — the maximally reusable read-only signature.
Casting const away is a promise
Writing through a cast-away-const pointer is UB if the object is truly const — only do it when you know the origin is mutable.
#include <stdio.h> size_t mylen(const char *s) { size_t n = 0; while (*s++) ++n; return n;} int main(void) { printf("%zu\n", mylen("hello")); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.