Search code examples
cpointersrestrict-qualifier

Can a function return an argument that is a restrict pointer?


Say I have a function that takes 2 non-aliased int*, and copies one int into the other, then returns the int* that served as the destination. For example:

int* copy_int(int* restrict dest, int const* restrict src) {
    *dest = *src;
    return dest;
}

Is any of the following calling code undefined behaviour?

void caller(void) {
    int dest;
    int src = 42;

    copy_int(&dest, &src);  // ignored return value aliases &dest
}
void caller(void) {
    int dest;
    int src = 42;

    int* dest_addr = copy_int(&dest, &src);  // dest_addr aliases &dest
}
void caller(void) {
    int dest;
    int src = 42;

    int* dest_addr = &dest;
    int* dest_addr_2 = copy_int(&dest, &src);  // dest_addr_2 aliases dest_addr
}

Or am I safe to assume that restrict only applies inside the callee, and that I can alias those pointers outside the function call?


Solution

  • restrict applies to inside copy_int(int* restrict dest, int const* restrict src) in what the function can assume - leading to better optimized code. The caller is obliged to pass addresses that do not overlap data.

    All cases do the same thing in that regard: copy_int(&dest, &src);. dest and src are not aliasing each other. The aliasing cases presented by OP do not affect dest, src.

    Example of bad code below.

    copy_int(&src, &src);  // bad