</>EmbeddedInterview

What does the restrict keyword mean?

HardC Programming

Short answer: restrict (C99) applies to a pointer and is a promise from the programmer that, for the lifetime of that pointer, the object it points to is accessed only through that pointer (or pointers derived from it). This lets the compiler assume no aliasing, keep values in registers and vectorise loops. If the promise is broken, the behaviour is undefined.

void add(int *restrict dst, const int *restrict a, const int *restrict b, size_t n)
{
    for (size_t i = 0; i < n; i++)
        dst[i] = a[i] + b[i];
}

Why it helps

Without restrict, the compiler must assume dst might overlap a or b. After every store to dst[i], it has to reload a and b from memory, and it cannot safely load several elements at once with SIMD (Neon/Helium) instructions. With restrict, it can.

A smaller example of the effect:

int f(int *p, int *q) { *p = 1; *q = 2; return *p; }        /* must reload *p: q may equal p */
int g(int *restrict p, int *restrict q) { *p = 1; *q = 2; return *p; }   /* returns 1 directly */

Standard library uses: memcpy(void *restrict dst, const void *restrict src, size_t n) is declared with restrict, which is the formal reason overlapping buffers are undefined for memcpy (and why memmove, without restrict, must exist). printf, strcpy and sprintf use it too.

When to use it: performance-critical loops in DSP code (filters, FFT, image processing) on Cortex-M4/M7/M55 and Cortex-A, where you know the buffers never overlap. Check the generated assembly to confirm it helped.

Notes: C++ has no restrict keyword (compilers offer __restrict__/__restrict). It only matters for optimisation; removing it never changes the meaning of a correct program.