When to use restrict and when not to

I think you're right that it wouldn't hurt. Your loop pointer (call it p) will equal encodedEnd at the end of the loop. But nothing need be accessed after the loop (from either p or encodedEnd), so that shouldn't be a problem. I don't think it will help, either, because nothing is ever written or read from encodedEnd so there's nothing to optimize away.

But I agree with you having the first two restrict should really help.


In this particular case it won't make a difference whether encodedEnd is restrict or not; you have promised the compiler that no one aliases unencoded and encoded, and so the reads and writes won't interfere with each other.

The real reason that restrict is important in this case is that without it the compiler can't know that writes through encoded won't affect reads through unencoded. For example, if

encoded == unencoded+1

then each write to encoded would affect each subsequent read from unencoded, so the compiler can't schedule the load until the write has completed. restrict promises the compiler that the two pointers don't affect the same memory, so it can schedule loads far enough ahead to avoid pipeline stalls.


Try Mike Acton's article here (old link). Restrict is frightening because of both the performance implications of not using it and the consequences of using it incorrectly.

In your case, it sounds like you could safely apply restrict to all three pointers as none alias the same memory area. However there is going to be little to no performance benefit from using it on the third pointer.