Arguments passing in C | Call by value | Call by reference

Preview
You must first complete Introduction to function in C Language before viewing this Lesson

Arguments passing in C

Arguments can be passed to a function in two ways:

  • Call by value
  • Call by reference

Call by Value

In this case, actual arguments are copied to formal arguments one after another. Changes made to the formal arguments have no effect on the actual arguments .

Program
#include<stdio.h>
void show(int a)
{
a++;
printf(“\n%d”,a);
}
int main()
{
int x=100;
printf(“\n%d”,x);
show(x);
printf(“\n%d”,x);
return(0);
}
Output
100
101
100



Call by reference

In this case, the addresses of actual arguments are sent to formal arguments. Changes to formal arguments will also change actual arguments.

Program
#include<stdio.h>
void show(int *a)
{
(*a)++;
printf(“\n%d”,*a);
}
int main()
{
int x=100;
printf(“\n%d”,x);
show(&x);
printf(“\n%d”,x);
return(0);
}
Output
100
101
101



 

Passing Array as function argument

Arrays can also be passed as function arguments just as normal variables. 

i. Passing one dimensional array as function argument

In case of one dimensional array, we need to write the name of one dimensional array(Actual argument) within the parenthesis without pair of square brackets after function name.

In formal argument, we must write name of array along with square brackets with or without size.

Program
#include<stdio.h>
void show(int a[])
{
int i;
printf(“\nArray elements are: “);
for(i=0;i<4;i++)
printf(“\n%d”,a[i]);
}
int main()
{
int x[4]={4,5,7,3};
show(x);
return(0);
}
Output
Array elements are:
4
5
7
3



ii. Passing a two dimensional array as function argument

In case of two dimensional array, we need to write the name of two dimensional array(Actual argument) within the parenthesis without square brackets.

In formal argument, we should write array named as well as square brackets. First pair of square brackets may not contain size but second pair must have size.

Program
#include<stdio.h>
void show(int a[][2],int m,int n)
{
int i,j;
printf(“\nMatrix within function is: “);
for(i=0;i<m;i++)
 {
     printf(“\n”);
     for(j=0;j<n;j++)
     {
          printf(“\t%d”,a[i][j]);
     }
 }
}
int main()
{
int x[2][2]={5,7,6,87};
show(x,2,2);
return(0);
}
Output
Matrix within function is:
5       7
6       87

 

Best Books of C





Lesson tags: call by reference in c, call by value in c, one dimensional array as function argument in c, passing argument to a function in c, two dimensional array as function argument in c
Back to: C Programming Language