Course contentsShow
← C
Lesson 915 of 1,21913. Advanced CFree lesson

The `restrict` pointer qualifier

The restrict pointer qualifier

What you'll learn: How to use the restrict keyword to tell the compiler that a pointer is the sole mediator for the data it points to, enabling faster code execution.

The Problem: Pointer Aliasing

Imagine you are a chef with two assistants. You tell Assistant A to update the "Salt" bowl and Assistant B to check the "Seasoning" bowl. If "Salt" and "Seasoning" are actually the same bowl, Assistant B’s job depends on exactly when Assistant A finishes.

In C, this is called aliasing. If two pointers point to the same memory location, the compiler has to be extremely cautious. It can’t optimize or reorder instructions because it fears that changing data through ptr1 might unexpectedly change the data being read by ptr2. This caution makes your programs slower.

Enter restrict

The restrict qualifier is a pinky-promise to the compiler. When you declare a pointer as int *restrict ptr, you are saying: "For the lifetime of this pointer, only this specific pointer (or values derived directly from it) will be used to access the object it points to."

Because the compiler now knows no other pointer will "sneak in" and change that memory, it can perform aggressive optimizations, such as caching values in registers or reordering assembly instructions for better pipelining.

A Concrete Example

Consider a function that adds two vectors into a third:

void add_vectors(int n, int *restrict a, int *restrict b, int *restrict result) {
    for (int i = 0; i < n; i++) {
        result[i] = a[i] + b[i];
    }
}

By using restrict, you guarantee that the result array does not overlap with a or b. Without restrict, the compiler would have to worry: "What if result and a share the same memory? I better reload a[i] from memory every single loop iteration just in case the last write to result[i] changed it." With restrict, the compiler can load values much more efficiently, knowing they won't change unexpectedly.

Important Note

The restrict keyword is for optimization, but it is also a contract. If you mark a pointer as restrict and then proceed to access that same memory through another pointer, you have broken the contract. This results in undefined behavior, which can lead to silent data corruption or crashes that are incredibly hard to debug.

Key takeaway

The restrict qualifier promises the compiler that a pointer is the only way to access a chunk of data, allowing for significantly faster, optimized machine code.