c / intermediate
Snippet
Optimization with the restrict Qualifier
The 'restrict' keyword is a hint to the compiler that the pointer is the only means to access the object it points to within that scope. This eliminates potential 'pointer aliasing', allowing the compiler to perform aggressive optimizations like vectorization.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>void vector_add(int * restrict a, int * restrict b, int * restrict result, int n) {for (int i = 0; i < n; i++) {result[i] = a[i] + b[i];}}int main() {int arr1[] = {1, 2, 3};int arr2[] = {4, 5, 6};int res[3];vector_add(arr1, arr2, res, 3);printf("Result: %d %d %d\n", res[0], res[1], res[2]);return 0;}
Breakdown
1
int * restrict a
Informs the compiler that pointer 'a' does not overlap with 'b' or 'result' in memory.
2
result[i] = a[i] + b[i];
Because of restrict, the compiler knows that writing to result[i] won't affect values in a[i] or b[i].