Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 629
no_stupid_questions Avatar asked Mar 01 '26 09:03

no_stupid_questions


1 Answers

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
like image 88
chux - Reinstate Monica Avatar answered Mar 02 '26 21:03

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!