Microcontroller Embedded C Programming Lecture 44| Returning data from a function

  • Post author:
  • Post category:Blog

 

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).  

Returning data from a function
Figure 1. Exercise

 

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

return data type
Figure 2. Exercise

 

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).

return data type
Figure 3. Output

 

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

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.

Leave a Reply