Search code examples
cpointersrestrict-qualifier

Usage of restrict on two pointers pointing to same array


I'm having quite hard time making proper usage of restrict keyword in C. I wrote this function to in-place reverse a string:

void my_strrev(char *restrict str, const size_t len) {
    char *restrict strr = str + len - 1;
    char temp;
    while (str < strr) {
        temp = *str;
        *str++ = *strr;
        *strr-- = temp;
    }
}

Here, although both str and strr are pointing to same array, I'm using those pointers to access individual characters, and they never point to same characters. Hence I think this is a proper use of restrict. Also I got expected output when I run this program with few sample inputs. But I'm unsure of my usage of restrict. So, please correct me if I'm doing wrong.


Solution

  • restrict has pretty much one single use - a contract that the programmer signs up with the compiler saying "I promise that I won't pass parameters pointing at the same data to this function with external linkage." This is still to this day mostly based on the compiler trusting the programmer, rather than the compiler giving diagnostic messages when the programmer "breaks the contract".

    If the compiler can assume that the programmer kept their side of the bargain, it can make optimizations:

    • It can assume that buffers passed to a function won't overlap - no need for temporary storage. (See memcpy vs memmove for example.)
    • It can assume that different pointer parameters aren't aliases of each other, pointing to the same data. (Which could be possible if you have for example a char* and an int* parameter.)
    • It can assume that pointer parameters aren't modifying any external linkage resources ("globals") used by the function, but that all access to what the pointer points at happens through that pointer.

    Using restrict for a local pointer variable isn't very meaningful since it doesn't relate to any of the above situations. It will compile but there will be no benefits of using it. As far as I know, no additional diagnostics is currently provided by any of the mainstream compilers, should you use a restrict pointer inappropriately.