c / intermediate
Snippet
Optimization with the restrict Keyword
The 'restrict' qualifier is a hint to the compiler that for the lifetime of the pointer, only the pointer itself or a value derived from it will be used to access the object it points to. This allows the compiler to perform optimizations like vectorization that would otherwise be unsafe due to potential pointer aliasing.
snippet.c
1
2
3
4
5
void add_arrays(int *restrict a, int *restrict b, int *restrict result, int n) {for (int i = 0; i < n; i++) {result[i] = a[i] + b[i];}}
Breakdown
1
int *restrict a
Tells the compiler that 'a' points to a unique memory block not aliased by 'b' or 'result'.
2
result[i] = a[i] + b[i];
The compiler can safely load values from 'a' and 'b' into registers without worrying that 'result' might overwrite them.