restrict

In the C programming language, as of the C99 standard, restrict is a keyword that can be used in pointer declarations. The restrict keyword is a declaration of intent given by the programmer to the compiler. It says that for the lifetime of the pointer, only the pointer itself 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 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]

C++ does not have standard support for restrict, but many compilers have equivalents that usually work in both C++ and C, such as the GNU Compiler Collection's and Clang's __restrict__, and Visual C++'s __restrict and __declspec(restrict).

In the above code, the pointers ptrA, ptrB, and valmight refer to the same memory location, so the compiler may generate less optimal code:

loadR1←*val; Load the value of val pointerloadR2←*ptrA; Load the value of ptrA pointeraddR2+=R1; Perform AdditionsetR2→*ptrA; Update the value of ptrA pointer; Similarly for ptrB, note that val is loaded twice, because; ptrA may be equal to val (i.e., point to the same location).loadR1←*valloadR2←*ptrBaddR2+=R1setR2→*ptrB

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

then the compiler is allowed to assume that ptrA, ptrB, 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:

loadR1←*valloadR2←*ptrAaddR2+=R1setR2→*ptrA; Note that val is not reloaded,; because the compiler knows it is unchangedloadR2←*ptrBaddR2+=R1setR2→*ptrB

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

^Ulrich Drepper (October 23, 2007). "Memory part 5: What programmers can do". What every programmer should know about memory. lwn.net. ...The default aliasing rules of the C and C++ languages do not help the compiler making these decisions (unless restrict is used, all pointer accesses are potential sources of aliasing). This is why Fortran is still a preferred language for numeric programming: it makes writing fast code easier. (In theory the restrict keyword introduced into the C language in the 1999 revision should solve the problem. Compilers have not caught up yet, though. The reason is mainly that too much incorrect code exists which would mislead the compiler and cause it to generate incorrect object code.)