Search code examples
pointersc99strict-aliasingrestrict

Useless case for restrict


So my understanding is that the C99 standard mandates that pointers to different types should not be aliased (i.e. pointed to the same memory). The restrict keyword assures the compiler that two certain variables (of the same type?) are not located in the same memory slot.

Therefore, is it true, that the following function would not profit form the restrict keyword?

void sphere_intersect(float* t, const sphere* s, const ray* r); 

But, a function like this would:

void vector_add(vector* v, const vector* u);

Solution

  • A function like

    void sphere_intersect(float* t, const sphere* s, const ray* r);
    

    could benefit from adding restrict if the types sphere and/or ray contain any float fields. Absent restrict, the compiler must assume that t might alias with any float field in the objects pointed at by s or r. So any write to *t might modify such a field meaning that the compiler could not hold the value of said field in a register for later reuse, but would instead have to reload it.