I have the following simple function
static inline void
minVec(const double *restrict v, double *restrict vmin, unsigned length){
for (unsigned i = 0; i < length; ++i)
vmin[i] = -v[i];
return;
}
which compiles and runs just fine when I use it this way
double v[] = {1, 2, 3};
minVec(v, v, 3);
I've been led to believe that using restrict in this case only informs the compiler that each iteration of the loop is independent of the others, so the loop can be aggressively optimized. Is this the correct way of doing it or am I poking with some implementation-defined behaviour here?
The restrict keyword is purely an optimization hint: it allows the compiler to reorder reads/writes from/to the restricted pointers with all other memory accesses. This cannot be done if the compiler cannot prove that the memory behind a pointer can only accessed via that pointer.
So, if you say restrict, you effectively tell the compiler: "I assure you this pointer is the only one that points to this memory, please feel free to reorder. I am fully aware that blue elephants may appear if I am wrong, but I'm the human, I can't be wrong, bow before me."
This keyword is for the sake of the compiler, not for your sake!
The use of restrictkeyword indicates that the source of the copy and the destination shouldn't overlap. It doesn't guarantee that source of the copy and destination doesn't overlap. If it happens, program invokes undefined behavior, which is what happening in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With