i have been trying to figure out ways where i can return more than one value from a function in C.
Say for instance i have the
int compute(int a, int b)
{
int c;
// do some computation on a,b,c
// return a,b,c
}
now i can return these values say in an array, and i was trying to do that and i then i realized that the array needs to be dynamic so it can be referenced in main() as well.
Another way could be that i create a structure and then just return the struct variable.
Is there any simple and robust way of doing this, other than the above work around ? i have to return about 25 different computation values which are independent of each other from a method, and i have a lot structs in my code already.
Thank you.
You can’t easily return more than one variable like, for example, Python with
return (a,b,c). However you can pass pointers that are set to the other “return values” or use a struct.Out-of-place
If you want a function to actually return separate values and not modify its arguments, a simple way is to pass additional pointers (you could also use structs). e.g. this function will compute the sum and difference of a pair of numbers:
The
if (ret1)allows you to safely passNULLas the pointer argument, so that you can ignore that return value. You use this like:(Note, this technique can lead to confusing behaviour if you pass the same argument twice, e.g.
a = add_sub(a, b, &b)doesn’t give you what want.)In-place
If you want to modify the arguments to a function, you can just pass those as pointers. e.g. this function will increment both its arguments and then return their sum:
Which you use like:
(Note that you can’t use literals in
increment_and_sum, that is, you can’t doincrement_and_sum(3, 4)orincrement_and_sum(&3, &4).)