Search code examples
cpointersreturn-value

Is it better to use a pointer instead of returning a value?


I was wondering what is the best way to get a value from a function. A function can return a value like an int for example. But you can also change the value of a variable with a pointer passed as a parameter to the function. See below, two examples of codes that do this in two different ways, but produce the same result.

int example_return()
{
    return (1);
}

int main(void)
{
    int value;

    value = example_return();
}
void    example_ptr(int *a)
{
    *a = 1;
}

int main(void)
{
    int value;

    example_ptr(&value);
}

Is there a real difference between the two options, which is the best way?


Solution

  • Side effects should be avoided if not absolutely needed. If you can return the value - return it. Basically, the function should a black-box which does something with parameters and returns the value.

    Why:

    1. It is much safer. You definitely will not invoke undefined behaviour.
    2. It helps the compiler to optimize the code.

    In your example -

    int example_return(void)
    {
        return (1);
    }