If I got the C99 restrict
keyword right, qualifying a pointer with it is a promise made that the data it references won\'t be modified behind the compiler\'s back t
Chris Dodd has the correct description of the keyword. In certain platforms it can be very important for performance reasons, because it lets the compiler know that once it has loaded data through that pointer onto a register, it need not do so again. Without this guarantee, the compiler must reload the data through a pointer every time any other possibly-aliasing pointer is written through, which can cause a serious pipeline stall called a load-hit-store.
const
and restrict
are different concepts, and it is not the case that const
implies restrict
. All const
says is that you will not write through that pointer within the scope of that function. A const
pointer may still be aliased. For example consider:
int foo( const int *a, int * b )
{
*b *= 2;
return *a + *b; // induces LHS: *a must be read back immediately
// after write has cleared the store queue
}
While you cannot directly write to a
in this function, it would perfectly legal for you to call foo like:
int x = 3;
foo( &x, &x ); // returns 12
restrict
is a different guarantee: a promise that a != b
in all calls to foo()
.
I've written about the restrict keyword and its performance implications at length, and so has Mike Acton. Although we talk about a specific in-order PowerPC, the load-hit-store problem exists on the x86 as well, but the x86's out-of-order execution makes that stall harder to isolate in a profile.
And just to emphasize: this is not an arcane or premature optimization, if you care about performance at all. restrict
can lead to really significant speedups if used correctly.