Table of Contents

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:

Performance impact:

When to use:

Gotchas:

Common violations:

Alternatives: