Most definitions of restrict say that it's a promise from the programmer to the compiler that for the lifetime of the pointer, the pointer is the only way that object is accessed. This allows the compiler to optimize the output, because it knows that it will be accessed only by one pointer and thus can be changed only by it. Which if I understand correctly usually means that the program doesn't have to reload the value the pointer points to.
If this is correct then there should be some exceptions when the restrict keyword should be usable even if it goes against the intent of how it should be used.
One thing that comes to mind would be when the data the pointer points to never actually changes during the lifetime of the pointer. In such case there is no need to reload the data even if the pointers point to the same location, because they don't change in the lifetime of the pointers. E.g.:
int max(int *restrict a, int *restrict b) {
return((*a > *b) ? *a : *b);
}
int main(void) {
int num = 3;
int max = max(&num, &num);
}
Is this a valid use of restrict even though it goes against how it was supposed to be used? Will using the restrict keyword like this result in undefined behaviour?
As Eric says the in a comment that is now gone, the key phrase from the C99 draft standard
6.7.3.1 Formal definition of restrict
is:
`If… X is also modified…`
this interpretation is supported by this example in 6.7.3.1/10
:
void h(int n, int * restrict p, int * restrict q, int * restrict r)
{
int i;
for (i = 0; i < n; i++)
p[i] = q[i] + r[i];
}
and the following comment with the code sample:
illustrate how an unmodified object can be aliased through two restricted pointers. In particular, if a and b are disjoint arrays, a call of the form h(100, a, b, b) has defined behavior, because array b is not modified within function h.
So it would seem that your specific example is defined behavior
since you are not modifying a
or b
.
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