restrict qualification
suggest changeIf a function has two pointer arguments of the same type, the compiler cannot assume they refer to different objects. It has to allow for a store through *e changing *f:
#include <stdio.h>
void fun(float *e, float *f) {
float a = *f;
*e = 22;
float b = *f;
printf("is %g equal to %g?\n", a, b);
}
int main(void) {
float fval = 4;
float eval = 77;
fun(&eval, &fval);
}
With those distinct objects the program prints something like
is 4 equal to 4?
If the same pointer is passed for both arguments, the program still does the right thing and prints
is 4 equal to 22?
That caution can be inefficient when the caller knows that e and f never point at the same object. restrict on the pointer parameters records that promise:
#include <stdio.h>
void fun(float *restrict e, float *restrict f) {
float a = *f;
*e = 22;
float b = *f;
printf("is %g equal to %g?\n", a, b);
}
The compiler may then assume that e and f point to different objects. Passing the same object for both arguments breaks that promise and is undefined behavior.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents