I came across a tutorial the other day that said a function can
return more than one value. How is this done? Pointers. Can someone
please show me an example. Say I want to return a double or an int.
A function can only return one value as its return value, but it can
achieve the effect of multiple return values by taking pointers as
arguments and storing its "return" values in the locations pointed to
by that pointer. So you can't write anything like
//NOT VALID C
int, double myfunc(void) { return 1, 3.14159; }
void someotherfunc(void)
{
int eger; double talk;
eger, talk = myfunc();
}
//NOT VALID C
but you can "return" both an int and a double like this:
void myfunc(int *errupt, double *dutch)
{
*errupt = 3; // returning int value through "output parameter"
*dutch = 0.14159; // returning double value through "output param"
}
void sometherfunc(void)
{
int elligent;
double t;
myfunc(&elligent, &t);
printf("%d %f\n", elligent, t);
}
This technique is also useful even when you want to return just one value,
but want to have a way to signal success or failure, without reserving
any special return value to indicate failure:
/* Returns 0 for success, non-zero for failure
* Numerical result stored in *resultp
*/
int do_something(int *resultp)
{
// ...
if (/* some error condition */) return 1;
// ...
*resultp = result;
return 0;
}