In the C programming language, as of the C99 standard,
restrict is a keyword which may be used when declaring pointers. The
restrict keyword is a message from the programmer to the compiler saying 'this is the only pointer to that memory block'. The data pointed to by a pointer declared with the
restrict qualifier may not be pointed to by any other pointer, or strange runtime behavior may result.
If the compiler knows that there is only one pointer to a memory block, it can produce better code. The following example makes it clear:
In the above code, the pointers
val might refer to the same memory location, so the compiler will generate a less optimal code :
However if the
restrict keyword is used and the above function is declared as
void UpdatePtrs(size_t* restrict ptrA, size_t* restrict ptrB, size_t* restrict val)
then the compiler is allowed to assume that
val point to different locations and updating one pointer will not affect the other pointers. The programmer, not the compiler, is responsible for ensuring that the pointers do not point to identic locations.
Now the compiler can generate better code as follows:
Note that the above assembly code is better and the
val is loaded once.
Another example is of
memcpy. The two pointers used as arguments to
memcpy(void*, void*, nbytes) are declared with
restrict, which tells the compiler of the
memcpy function that the two data areas do not overlap. This allows the compiler to produce a faster
memcpy function. A programmer might send the same pointer as both arguments, in which case behavior of the
memcpy function is undefined.