Thursday, March 3, 2016

Function with Return Value

Function as mentioned earlier can return some value. The number of values that can be returned by a function is restricted to 1 in C. If a function calculates more number of output values, you can use a structure/union to hold each of them and return it. The type of value returned by the function must be defined in the function prototype and definition. To illustrate function with return value a simple program is presented below.

  1. #include<stdio.h>
  2. int add(int a, int b);
  3.  
  4. void main()
  5. {
  6. int sum = 0;
  7. sum = add(23, 35);
  8. printf("Sum : %d", sum);
  9. }
  10.  
  11. int add(int a, int b)
  12. {
  13. int c = a + b;
  14. return c;
  15. }
In the above example, the function 'add()' takes two arguments of integer type and returns an integer value. Notice the return statement in the 'add()' function which returns the value to the caller.

No comments: