Types of function

Function call type

  1. call by value – When we pass actual value of an argument into formal argument of the function is called,  call by value. In this type of function call  any changes in formal argument inside called function does not effect the actual argument.
  2. call by reference – When we pass address of an argument into formal argument of the function is called, call by reference. The address is used to access actual argument inside called function. In this case changes made to argument effect the actual argument.

Example of  call by value

  1. #include<stdio.h>
  2. void gt_func2(int x, int y); /* Function prototype */
  3. int main()
  4. {
  5.     int num1 = 10;
  6.     int num2 = 40;
  7.     gt_func2(num1, num2); /* Function call */
  8.     printf(“num1 = %d\n”,num1);
  9.     printf(“num2 = %d\n”,num2);
  10.     return 0;
  11. }
  12. void gt_func2(int x, int y) /* Function definition */
  13. {
  14.     x = 20;
  15.     y = 50;
  16.     printf(“x = %d\n”,x);
  17.     printf(“y = %d\n”,y);
  18. }

Output of this program is :-
$ ./a.out
x = 20
y = 50
num1 = 10
num2 = 40

Explanation :-
We can see in above C program  num1, num2 is actual argument and  x , y is formal argument.  Changes in formal argument is not effecting actual argument.

Example of call by reference

  1. #include<stdio.h>
  2. void gt_func2(int *x, int *y); /* Function prototype */
  3. int main()
  4. {
  5.     int num1 = 10;
  6.     int num2 = 40;
  7.     gt_func2(&num1, &num2); /* Function call */
  8.     printf(“num1 = %d\n”,num1);
  9.     printf(“num2 = %d\n”,num2);
  10.     return 0;
  11. }
  12. void gt_func2(int *x, int *y) /* Function definition */
  13. {
  14.     *x = 20;
  15.     *y = 50;
  16.     printf(“x = %d\n”,*x);
  17.     printf(“y = %d\n”,*y);
  18. }

Output of this program is :-
$ ./a.out
x = 20
y = 50
num1 = 20
num2 = 50

Explanation :-
We can see in above C program  num1, num2 is actual argument and  x , y is formal argument. We are sending address of formal argument and receiving through pointer in called function. We will study about pointer in next chapter. In output we can see, changes in formal argument is effecting actual argument.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.