Passing Parameters to functions in C Programming

When a function is called, the calling function has to pass some values to the called functions.

There are two ways by which we can pass the parameters to the functions:

1. Call by value

  • Here the values of the variables are passed by the calling function to the called function.
  • If any value of the parameter in the called function has to be modified the change will be reflected only in the called function.
  • This happens as all the changes are made on the copy of the variables and not on the actual ones.

Example: Call by value

#include <stdio.h>
int sum (int n);
void main()
{
     int a = 5;
     printf("\n The value of 'a' before the calling function is = %d", a);
     a = sum(a);
     printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int n)
{
     n = n + 20;
     printf("\n Value of 'n' in the called function is = %d", n);
     return n;
}


Output:
The value of 'a' before the calling function is = 5
Value of 'n' in the called function is = 25
The value of 'a' after calling the function is = 25

2. Call by reference

  • Here, the address of the variables are passed by the calling function to the called function.
  • The address which is used inside the function is used to access the actual argument used in the call.
  • If there are any changes made in the parameters, they affect the passed argument.
  • For passing a value to the reference, the argument pointers are passed to the functions just like any other value.

Example: Call by reference

#include <stdio.h>
int sum (int *n);
void main()
{
     int a = 5;
     printf("\n The value of 'a' before the calling function is = %d", a);
     sum(&a);
     printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int *n)
{
     *n = *n + 20;
     printf("\n value of 'n' in the called function is = %d", n);
}


Output:
The value of 'a' before the calling function is = 5
value of 'n' in the called function is = -1079041764
The value of 'a' after calling the function is = 25