capypad
0 day streak
c / expert
Snippet

Strict Aliasing and the restrict Keyword

Strict aliasing allows the compiler to assume that pointers of different types do not alias the same memory. The 'restrict' qualifier (C99) explicitly informs the compiler that for the lifetime of the pointer, only it (and pointers derived from it) will be used to access the object it points to. This enables aggressive optimizations, such as loading values into registers once instead of re-fetching them from memory due to potential side effects.

snippet.c
c
1
2
3
4
5
6
void vector_add(int * restrict a, int * restrict b, const int * restrict src, int n) {
for (int i = 0; i < n; i++) {
a[i] += src[i];
b[i] += src[i];
}
}
Breakdown
1
int * restrict a
Tells the compiler that 'a' is the unique access path to its memory block.
2
b[i] += src[i];
The compiler knows 'src' wasn't modified by the previous write to 'a', avoiding a reload.