Questionable
Questionable

Reputation: 878

Does using `restrict` when initializing a new pointer actually do anything?

I have been reading about the restrict keyword and every example I've seen uses it when defining a function.

void foo (int *restrict bar, float *restrict baz);

I have been reading through articles on it and wondering if this would be something valid.

int main()
{
    int *restrict bar = malloc(sizeof(int));
    //... code using bar
    return 0;
}

I tested it with gcc and I am not receiving any compiler warnings, but will it actually do anything? Will the compiler pick up that this pointer for it's life will not overlap and that it will not be shared by any other pointer or will it only work when used when defining a function?

Upvotes: 1

Views: 170

Answers (1)

dash-o
dash-o

Reputation: 14452

The restricted 'bar' in main tell the compiler that the data will not be referenced via any other pointer. Depending on what main does, it might help with optimization of 'main'. If the only manipulation of bar is in function foo, there is no need to make it restrict.

As a side note, on Linux/gcc, the 'malloc' is tagged with __attribute__ ((__malloc__)), which tells the compiler that the returned value is restrict pointer, which will allow the compiler the perform the required optimization, if relevant. See: understanding malloc.h difference: __attribute_malloc__ https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html

malloc

This tells the compiler that a function is malloc-like, i.e., that the pointer P 
returned by the function cannot alias any other pointer valid when the function
returns, and moreover no pointers to valid objects occur in any storage addressed by P.

Using this attribute can improve optimization. Compiler predicts that
a function with the attribute returns non-null in most cases.
Functions like malloc and calloc have this property because they
return a pointer to uninitialized or zeroed-out storage. However,
functions like realloc do not have this property, as they can return a
pointer to storage containing pointers.

Upvotes: 3

Related Questions