CC Explainer
C · 2 · Memory & Pointers11 / 35 · 31%

const Correctness & void*

Read declarations right-to-left, and use void* for generic code.

Examples: const char *, char * const, qsort

shortcuts: ← prev · → next · M mark
1

Read It Right-to-Left

The position of const relative to * decides what is frozen.

Example
example
const int *p;        // pointer to const int   (can't write *p)
int const *p2;       // identical to the above
int * const p3 = &x; // const pointer to int   (can't move p3)
const int * const p4 = &x; // both frozen
2

const in APIs

A const parameter is a promise to the caller that you won't modify the data.

Example
example
size_t my_strlen(const char *s) {
    size_t n = 0;
    while (s[n]) n++;
    return n;   // s is never written through
}
const on input pointers also enables better optimization and self-documents intent.
3

void* — Generic Pointers

void* holds any object address, but you cannot dereference it directly.

Example
example
void *mem = malloc(n * sizeof(int));
int  *ints = mem;               // implicit conversion is fine in C
// *mem;                        // error: incomplete type

int cmp(const void *a, const void *b) {
    return (*(const int*)a) - (*(const int*)b);
}
qsort(ints, n, sizeof(int), cmp);
4

Casting Away const

Legal syntax, undefined behavior if the object was really const.

Example
example
const int k = 5;
int *bad = (int*)&k;
*bad = 9;   // UNDEFINED BEHAVIOR — k may live in read-only memory
WATCH OUT
If you need to cast away const, the API is usually wrong. Fix the signature instead.