Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use restrict and when not to

Tags:

I have a general understanding of restrict but I'm hoping to clarify some fine points. I have a function that reads a null-terminated string from one buffer and writes out a URL encoded version in another buffer. The function has this signature (currently without restrict):

char const *StringUrlEncode(char const *unencoded,                              char *encoded,                             char *encodedEnd); 

unencoded is my null-terminated source string. The destination buffer is represented by encoded and encodedEnd, where encoded points to the first char in the buffer and encodedEnd points to the first char after the buffer, i.e. the function will write chars up to but not including the location pointed to by encodedEnd -- this is your basic begin/end iterator pair if you're familiar with C++ STL conventions.

If I add restrict to this function, should it only be applied to the first two parameters:

char const *StringUrlEncode(char const *restrict unencoded,                              char *restrict encoded,                             char *encodedEnd); 

or is there some benefit I'm not understanding by adding it to all three parameters?

I can see that making the input and output buffers restrict helps the compiler know that they don't overlap. But since the last parameter, encodedEnd, is only used to mark the end of the output buffer, I'm thinking that restrict wouldn't really be any help to the compiler here (though I assume it wouldn't hurt, other than adding unnecessary noise to the function declaration).

like image 980
Don McCaughey Avatar asked May 07 '09 05:05

Don McCaughey


People also ask

What is restrict keyword used for?

The restrict keyword is a feature of the C99 standard that can be useful to C/C++ programmers. It can be attributed to pointers to guarantee that no other pointer overlaps the referenced memory location. Using the Intel C++ compiler does not only limit it to C99.

What does * restrict mean in C?

In the C programming language, restrict is a keyword, introduced by the C99 standard, that can be used in pointer declarations. By adding this type qualifier, a programmer hints to the compiler that for the lifetime of the pointer, no other pointer will be used to access the object to which it points.


1 Answers

Try Mike Acton's article here (old link). Restrict is frightening because of both the performance implications of not using it and the consequences of using it incorrectly.

In your case, it sounds like you could safely apply restrict to all three pointers as none alias the same memory area. However there is going to be little to no performance benefit from using it on the third pointer.

like image 109
Dan Olson Avatar answered Oct 16 '22 15:10

Dan Olson