C restrict qualifier (C99) tells the compiler that a pointer is the only way to access that memory during its lifetime. Enables aggressive optimization assuming no aliasing. Declare as int * restrict ptr to promise no other pointers reference the same data.
Use restrict for performance-critical code like vector operations; compiler can eliminate redundant loads.
// compile: gcc -O2 -o restrict restrict.c // run: ./restrict // description: restrict qualifier for optimization #include <stdio.h> // Without restrict: compiler assumes aliasing void copy_slow(int *dst, const int *src, int n) { for (int i = 0; i < n; i++) { dst[i] = src[i]; } } // With restrict: compiler knows no aliasing void copy_fast(int * restrict dst, const int * restrict src, int n) { for (int i = 0; i < n; i++) { dst[i] = src[i]; } } // Vector operation void scale_vector(float * restrict v, const float * restrict scale, int n) { for (int i = 0; i < n; i++) { v[i] *= *scale; } } int main() { int src[10] = {1,2,3,4,5,6,7,8,9,10}; int dst[10]; copy_fast(dst, src, 10); printf("Copy successful: %d\n", dst[0]); return 0; }
Semantics:
Performance impact:
When to use:
Gotchas:
Common violations:
copy_fast(arr, arr+1, n)Alternatives: