tags:

views:

333

answers:

2

Just wondering: When I add restrict to a pointer, I tell the compiler that the pointer is not an alias for another pointer. Let's assume I have a function like:

// Constructed example
void foo (float* result, const float* a, const float* b, const size_t size)
{
     for (size_t i = 0; i < size; ++i)
     {
         result [i] = a [0] * b [i];
     }
}

If the compiler has to assume that result might overlap with a, it has to refetch a each time. But, as a is marked const, the compiler could also assume that a is fixed, and hence fetching it once is ok.

Question is, in a situation like this, what is the recommend way to work with restrict? I surely don't want the compiler to refetch a each time, but I couldn't find good information about how restrict is supposed to work here.

+3  A: 

Your pointer is const, telling anyone calling your function that you won't touch the data which is pointed at through that variable. Unfortunately, the compiler still won't know if result is an alias of the const pointers. You can always use a non-const pointer as a const-pointer. For example, a lot of functions take a const char (i.e. string) pointer as a parameter, but you can, if you wish, pass it a non-const pointer, the function is merely making you a promise that it wont use that particular pointer to change anything.

Basically, to get closer to your question, you'd need to add restrict to a and b in order to 'promise' the compiler that whoever uses this function won't pass in result as an alias to a or b. Assuming, of course, you're able to make such a promise.

roe
+1  A: 

As the previous answer stated, you need to add "restrict". I also wanted to comment on your scenario that "result might overlap with a". That is not the only reason the compiler will detect that "a" could change. It could also be changed by another thread that has a pointer to "a". Thus, even if your function did not change any values, the compiler will still assume that "a" could change.