C/C++ Arena

Step 8 of 10

const and pointers

const can protect two different things, depending on where you put it:

Declaration Can change *p? Can re-point p?
const int *p no yes
int *const p yes no
const int *const p no no

Read it right to left: const int *p is "p is a pointer to an int that is const".

Professional C code marks every pointer parameter it only reads as const int *. It documents the promise ("I won't change your data") and the compiler enforces it.

A function can also return a pointer into the caller's array. If the array was const, the returned pointer must be const too.

Your turn: write const int *find(const int *a, int n, int target) that returns a pointer to the first element equal to target, or NULL if there is none.

Previous: Pointers to pointers Next: Two pointers from both ends