- Restrict
In the
C programming language , as of the C99 standard,restrict
is a keyword which may be used when declaring pointers. Therestrict
keyword is a message from the programmer to thecompiler saying 'this is the only pointer to that memory block'. The data pointed to by a pointer declared with therestrict
qualifier may not be pointed to by any other pointer, or strange runtime behavior "may" result.Optimization
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
ptrA
,ptrB
,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 asvoid UpdatePtrs(size_t* restrict ptrA, size_t* restrict ptrB, size_t* restrict val)
then the compiler is allowed to "assume" thatptrA
,ptrB
,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 tomemcpy(void*, void*, nbytes)
are declared withrestrict
, which tells the compiler of thememcpy
function that the two data areas do not overlap. This allows the compiler to produce a fastermemcpy
function. A programmer might send the same pointer as both arguments, in which case behavior of thememcpy
function is undefined.External links
* [http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html Demystifying The Restrict Keyword] : explanation and examples of use
Wikimedia Foundation. 2010.