The example is taken from Wikipedia:
void updatePtrs(size_t *restrict ptrA, size_t *restrict ptrB, size_t *restrict val)
{
*ptrA += *val;
*ptrB += *val;
}
I call this function in the main()
:
int main(void)
{
size_t i = 10;
size_t j = 0;
updatePtrs(&i, &j, &i);
printf("i = %lu\n", i);
printf("j = %lu\n", j);
return 0;
}
The val
pointer is not be loaded twice according to the Wikipedia's description, so the value of j
should be 10, but it's 20 in fact.
Is my comprehension about this keyword not correct? Should I utilize some specific options of gcc
?
Thanks in advance.
Your code causes undefined behaviour. restrict
is a promise from you to the compiler that all of the pointer parameters point to different memory areas.
You break this promise by putting &i
for two of the arguments.
(In fact, with restrict
it is allowed to pass overlapping pointers, but only if no writes are done through any of the overlapping pointers within the function. But typically you would not bother with restrict
if there is no writing happening).
FWIW, on my system with gcc 4.9.2, output is j = 20
at -O0
and j = 10
at -O1
or higher, which suggests that the compiler is indeed taking note of the restrict
. Of course, since it is undefined behaviour, your results may vary.