Home > OS >  C Return Value from Function Best Practice
C Return Value from Function Best Practice

Time:11-16

What option is recommended in C to return an array from a function?

Option 1:

void function_a(int *return_array){
    return_array[0] = 1;
    return_array[1] = 0;
}

Option 2:

int* function_b(){
    int return_array[2];
    return_array[0] = 1;
    return_array[1] = 0;
    return return_array;
}

CodePudding user response:

This function

int* function_b(){
    int return_array[2];
    return_array[0] = 1;
    return_array[1] = 0;
    return return_array;
}

returns a pointer to the first element of a local array with automatic storage duration that will not be alive after exiting the function.

So the returned pointer will be invalid and dereferencing such a pointer invokes undefined behavior.

You could return a pointer to first element of an array from a function if the array is allocated dynamically or has static storage duration that is when it is declared with the storage class specifier static.

As for the first function then it will be more safer if you will pass also the number of elements in the array like

void function_a(int *return_array, size_t n );

and within the function you will be able to check the passed value.

CodePudding user response:

I'd most prefer:

void function_a(int return_array[const], size_t sz) {
    return_array[0] = 1;
    return_array[1] = 0;
}

Because it clearly indicates that the parameter is an Array, and it also clearly indicates the size of the array that is passed in, making out-of-bounds indicies less likely to be a problem.

  • Related