Site Tools


c-restrict-qualifier

C restrict qualifier

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.

Example

// 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;
}

Common patterns

Semantics:

  • Promise to compiler: no other pointers alias this data
  • Compiler trusts you; violating it causes undefined behavior
  • Only matters for optimizer

Performance impact:

  • Can enable loop optimizations
  • Eliminate redundant memory loads
  • Vectorization opportunities
  • Modern CPUs already have prediction; impact varies

When to use:

  • Inner loops in algorithms
  • BLAS/linear algebra
  • Image processing
  • When profiling shows memory is bottleneck

Gotchas:

  • Lying about restrict = undefined behavior
  • Same memory accessed through non-restrict ptr = bug
  • Compiler won't warn; must be correct
  • Not all compilers respect restrict well

Common violations:

  • Overlapping source/dest: copy_fast(arr, arr+1, n)
  • Global variable accessed: restrict ptr to global
  • Function modifies restrict-pointed data

Alternatives:

  • Rely on compiler optimization
  • Use restrict only if proven necessary
  • Profile before optimizing
c-restrict-qualifier.md · Last modified: by 127.0.0.1