Does restrict help in C if a pointer is already marked const?

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.


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 (ie 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.


In the C-99 Standard (ISO/IEC 9899:1999 (E)) there are examples of const * restrict , eg, in section 7.8.2.3:

The strtoimax and strtoumax functions

Synopsis

#include <inttypes.h>
intmax_t strtoimax(const char * restrict nptr,
                   char ** restrict endptr, int base);
--- snip ---

Therefore, if one assumes that the standard would not provide such an example if const * were redundant to * restrict , then they are, indeed, not redundant.


Everyone here seems very confused. There's not a single example of a const pointer in any answer so far.

The declaration const float* a is not a const pointer, it's const storage. The pointer is still mutable. float *const a is a const pointer to a mutable float.

So the question should be, is there any point in float *const restrict a (or const float *const restrict a if you prefer).

链接地址: http://www.djcxy.com/p/64040.html

上一篇: C#中的内联函数?

下一篇: 如果指针已经标记为const,是否会在C中限制帮助?