C ‘restrict’ keyword

C ‘restrict’ keyword

In the C programming language, as of the C99 standardrestrict is a keyword that can be used in pointer declarations. The  restrictkeyword is a declaration of intent given by the programmer to the compiler. It says that for the lifetime of the pointer, only it or a value directly derived from it (such as  pointer + 1) will be used to access the object to which it points. This limits the effects of pointer aliasing, aiding caching optimizations. If the declaration of intent is not followed and the object is accessed by an independent pointer, this will result in undefined behavior. The use of the  restrict keyword in C, in principle, allows non-obtuse C to achieve the same performance as the same program written in Fortran.[1]



If the compiler knows that there is only one pointer to a memory block, it can produce better code. For instance:

In the above code, the pointers  ptrAptrB, and  val might refer to the same memory location, so the compiler will generate less optimal code :

However if the  restrict keyword is used and the above function is declared as :

then the compiler is allowed to assume that  ptrAptrB, and  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 identical locations.

Now the compiler can generate better code as follows:

Note that the above assembly code is shorter because  val is loaded once.

Leave a Reply