liveBook · Manning

Restrict

As explained in Modern C, Third Edition

restrict is a C type qualifier that lets an implementation assume an object is accessed through a designated pointer-based access path during a relevant execution.

In C, restrict qualifies a pointer and promises exclusive access to the object it designates during the relevant function execution. The compiler may use that promise when optimizing, but the caller must ensure it is true. section 16.2 section 16.5

memcpy versus memmove

The declarations make the contract visible:\n\nvoid *memcpy(void *restrict s1, void const *restrict s2, size_t n);\nvoid *memmove(void *s1, void const *s2, size_t n);\n\nFor memcpy, the accessed objects must not overlap, because both access paths require exclusivity. memmove makes no such assumption and therefore accepts equal or overlapping objects. section 16.2

Use restrict with these constraints in mind:

  • Treat qualification as a constraint on the function caller, not merely as an optimization hint inside the function. section 16.2
  • Ensure that each restrict-qualified access path provides exclusive access; violating the assumption makes the execution invalid. section 16.2
  • Remember that aliasing analysis matters: restrict is especially relevant when the compiler must determine whether pointers designate the same object. section 16.2
 void* memcpy(void*restrict s1, void const*restrict s2, size_t n);
 void* memmove(void* s1, const void* s2, size_t n);

Compare the restrict-qualified memcpy declaration with the unrestricted memmove declaration. section 16.2

How Modern C, Third Edition covers it

How deep it goes
Explains exclusive access, caller responsibility, aliasing, and memcpy versus memmove, but stops short of formal execution-context rules.
Examples
Uses memcpy and memmove declarations plus fputs, printf, and fprintf cases to expose overlapping-access violations.
What it assumes
Assumes familiarity with C pointers, function parameters, and library calls while defining exclusive access and aliasing through examples.
What you can do after
Apply restrict to function parameters when callers can guarantee exclusive access and use the promise to support optimization.
How it connects
Connects restrict with pointers, function parameters, aliasing, memcpy, memmove, fputs, and formatted input/output functions.

Also explained in

Compare how 2 books explain restrict →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.