Example 1 — Add two arrays element by element
The three arrays are distinct, so restrict is valid.
#include <stdio.h>
static void add_arrays(int n, int *restrict out,
const int *restrict a, const int *restrict b) {
for (int i = 0; i < n; i++) out[i] = a[i] + b[i];
}
int main(void) {
int a[] = {1, 2, 3};
int b[] = {4, 5, 6};
int out[3];
add_arrays(3, out, a, b);
printf("%d %d %d\n", out[0], out[1], out[2]);
return 0;
} How It Works
restrictsaysout,a, andbnever overlap.- The compiler can reorder or vectorize the loop.
- Calling
add_arrays(3, a, a, b)would break the promise.
