C99 Restrict

C

ccdrbrg

I'm having trouble understanding restrict.
Can someone provide a layman's explanation.

Chad
 
C

Christian Bau

I'm having trouble understanding restrict.
Can someone provide a layman's explanation.

"restrict" is there to help optimising compilers.

Example:

int f (int* x, int* y)
{
*x = 0;
*y = 1;
return *x;
}

Obviously this function will return 0. Except if x and y point to the
same object, in that case it will return 1. In practice, 99.99% of the
time the result will be 0. But a compiler must be right 100% of the
time. Therefore, an optimising compiler cannot replace this code with

int f (int* x, int* y)
{
*x = 0;
*y = 1;
return 0;
}

which would run faster. Would be nice if you could tell the compiler
that x and y don't point to the same object. So you write

int f (int *restrict x, int *restrict y)
{
*x = 0;
*y = 1;
return *x;
}

Roughly speaking, an lvalue is based on a "restrict" object if its
address has been calculated using that object. For example, the lvalue
"*x" is based on x. If you write "int* p = x + 3; int* q = p - 2; " then
the lvalue q is based on x, because its address is calculated in a
way that depends on the pointer object x.

If you use restrict pointers like int* restrict x, then you promise to
the compiler:

1. Anything that is modified through an lvalue based on x is not
accessed or modified through an lvalue that is not based on x.

2. Anything that is modified through an lvalue that is _not_ based on x
is not accessed or modifed through an lvalue that _is_ based on x.

If you use something like const int* restrict x, then you promise to the
compiler:

3. Anything that is accessed through an lvalue based on x is not
modified in any way.

Based on these promises, the compiler can produce faster code. If you
break the promise, then behavior is undefined.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top