Returning data from a function
Now let’s modify this function(Figure 1) to return a value to the caller. In this case, the main is the caller, and function_add_numbers is the callee(line 14).
And here, I used the void function_add_numbers(int a, int b, int c) function to compute the sum and return the sum back to the caller.
When the program execution control comes to the return sum, the value stored in the sum will be returned to the caller, and the control goes back to the caller.
So, here you are returning a data or value of integer type. That’s why the return data type has to be int now. So, instead of void, you mention int.
The value will be returned back to the caller(main), so, that’s why you have to catch that return value here(line 9), a value which is returned from the function.
For that, I created a variable int retValue. I caught the function here->retValue = function_add_numbers, and then print the return value, so printf(“Sum = %d\n”, retValue”);
When the function_add_numbers(12, 13, 0) function is called, a sum will be computed, and the sum will be returned, and that return value will be stored in the retValue variable. Then printf function prints the return value. We also have to change the prototype. Instead of a void, you mention int.
Then compile and build the program. So, you get the same output(Figure 3).
That’s about returning a value. So, you can return int type long int, char type, pointer type, so all those data types you can use as a return data type.
FastBit Embedded Brain Academy Courses
Click here: https://fastbitlab.com/course1