C Programming – Returning Multiple Values Using Pointers

c

What is good programming style for writing C-language functions and function calls to functions which return pointers?

For example, if I have a function my_function which return two integers through pointer arguments. How should I call this function, such that it is easy for a person who is not familiar with my code, to see that it returns two values?

And how should I write the function definition?

For example, I could always put the return values last in the parameter list, and
when I call the function, I could add some extra space to separate input arguments from return values.

Also, for the function definition, I could add an empty line with a comment between the input parameters and the return values. For example:

void my_function(
   int a,
   int b,
/* return values */
   int *c,
   int *d)
{
   /* do something */
}

int main()
{
   int a = 1;
   int b = 2;
   int c;
   int d;

   my_function(a,b,   &c, &d);
}

Best Answer

You could note the flow of information in the function definition:

void my_function(
   /*  in */ int  a,
   /*  in */ int  b,
   /* out */ int* c,
   /* out */ int* d)
{
   /* do something */
}

This way, it's easy to see what happens. If you export this function, you will also include the comments in the prototype so that everybody could see the direction of information flow.

Furthermore, adhere to one style in your functions. For example, if you write the return values always on the end of the parameter list and someone sees you calling

whatever(p1, p2, p3, &p4);

one will know that there's a high probability that p4 is the return value of your function.