restrict
type qualifierThe restrict
type qualifier was introduced in C language after the C99
standard. The restrict
type qualifier allows the programmer to declare restricted pointers - pointers that have exclusive access over a memory region. Restricted pointers allow the compiler to optimize the program’s memory access.
The structure of the restrict
type qualifier is as follows:
data_type restrict identifier
Note: Accessing the memory location of a restricted pointer using another pointer results in an undefined behavior.
restrict
type qualifierThe primary usage of the restrict
qualifier is in function arguments. The following function foo
takes in 3 integer pointers (a
, b
, and c
) and adds the value of c
to values of a
and b
:
Note: The word value here refers to the value at the memory location pointed by the pointers
a
,b
orc
.
void foo(int * a, int * b, int * c) {
*a += *c;
*b += *c;
}
The function above can be written using the restrict
type qualifier as well:
void foo(int * restrict a, int * restrict b, int * restrict c) {
*a += *c;
*b += *c;
}
The assembly code in this case is optimized to not reload the value at the memory address at c
after the line *a += *c;
is executed. Thus, one less instruction is required in the assembly code, and since executable code is one-to-one mapped with assembly code, there will also be one less instruction in the executable code.