In the previous post, we saw returning a single value from a function. What about a C function returns multiple values? Let’s say we have sent 2 numbers to our function and the function will return the result of addition and subtraction. See the code
If we run the code, you will see a garbage output of random value. Why? The straightforward answer is that a user-defined function returns multiple values in C is not allowed.
However, if you want it (a function returns multiple values), you can do it in another way, and the way is by using pointers. See the updated code below
Look at the code at line 11. We have passed 4 parameters.
- a, b: They are passed by value and their values will be received by num1 and num2 inside the function, respectively. Keep in mind that they have different memory locations. Anything the function do (changing values or other stuffs) with num1 and num2 will only be visible in the function() but not in the main().
- &add, &sub: They are passed by reference (as not their values, but their memory address is passed to the function). Anything the function do (changing values or other stuffs) with the addresses will be permanent, in other words, the changes will be visible both in the main() and in the function()
Now look at lines 6 and 7: we are assigning a value to the memory location of add by using the pointer *addition and the same goes for line 7. Here we are using pointer *subtraction to assign a value to the location of sub.
Now at line 14 and 15, we can print the values of add and sub to make yourself convinced your function is returning multiple values without explicitly writing even a single return statement inside the user defined function.
I hope I have explained it clearly. You can take a look at this book (Head First C: A Brain-Friendly) as well. It has some amazing explanations.
Thank you.