What does restrict promise to the compiler?
C++Level: IntermediateC Language Essentials
What does restrict promise to the compiler?
Hints
- Identify types, object lifetimes and compile-time decisions.
- Separate language guarantees from a particular compiler's behavior.
Answer
Restrict Qualifier
The restrict qualifier (C99) tells the compiler that a pointer is the only
way to access the pointed-to object, enabling aggressive optimizations. Without
restrict, the compiler must assume pointers might alias (point to overlapping
memory), preventing certain optimizations. Use restrict when you can
guarantee no aliasing, particularly in performance-critical functions like
memcpy().
#include <stdio.h>
// Without restrict, compiler assumes a and b might overlap
void add_arrays(int *a, int *b, int *result, int n) {
for (int i = 0; i < n; i++) {
result[i] = a[i] + b[i];
}
}
// With restrict, compiler can optimize more aggressively
void add_arrays_fast(int *restrict a, int *restrict b,
int *restrict result, int n) {
for (int i = 0; i < n; i++) {
result[i] = a[i] + b[i];
}
}
int main(void) {
int a[] = {1, 2, 3};
int b[] = {4, 5, 6};
int result[3];
add_arrays_fast(a, b, result, 3);
printf("%d %d %d\n", result[0], result[1], result[2]);
}
$ ./restrict
5 7 9
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT