Write about Call by Value and Call by Reference (or) Parameter Passing Techniques?


The techniques used to pass data from one function to another are known as parameter passing. “C” provides 2 mechanisms to pass arguments to a function.

1. Call by value (or) pass arguments by value.

2. Call by reference ( or) pass arguments by address ( or)pass arguments by pointers.

1. Call by value: 

In call by value the values of actual arguments are passed to the formal arguments and the operations are done on the formal arguments.

Any changes made in the formal arguments don’t effect the actual arguments because formal arguments are photo copy of actual arguments.

Hence the functions is called by using call by value method doesn’t effect the actual content of the actual arguments.

Changes made in the formal arguments are local to the block of called function. Once the control returned top the calling in them the changes made are vanished.

Ex: WAP for swapping of 2 numbers using call by value

#include
#includ
change ( int, , int);
main ( )
{
int a, b
clrscr ( );
printf (“enter a, b value”)
scanf ( “%d%d”, &a,&b);
printf (“\n before swapping values in main %d\n%d”, a,b);
change(a,b);
printf (“\n after swapping values in main %d\n%d”, a,b);
getch ( );
}

change ( int x, int y)
{
int z;
z=x;
x=y;
y=z;
printf ( “\n values in change function: %d \t %d”, x,y);
}


Call by reference:

In call by reference method instead of passing values adds are passed ( i.e. references) to the called function.

Here the function operates on address rather than value. The format arguments are pointers to the actual arguments. ie. Formal arguments point to the actual arguments.
Hence the changes made in the arguments are permanent.

In this case the called function directly works on the data in the calling functions and the changed values are available in the calling functions for its use.

Pass by pointers method to often used when manipulating arrays and strings.

This method is also used when we require multiple values to be returned by the called function.

Ex: WAP for swapping of 2 numbers using call by reference

change ( int *, int *);
main ( )
{
int a, b;
clrscr ( );
printf (“ \n enter a, b values “);
scanf (“%d%d”, &a,&b);
printf(“\n values before swapping %d\t%d”,a,b);
change ( &a, &b);
printf (“\n value after swapping %d \t %d”,a,b);
getch ( );
}

change  ( int *x, int *y)
{
int z;
z =*x;
*x=*y;
*y=z;
printf  ( “\n values in change function %d \t %d”, *x, *y);
}

Related

C Language 6374472592887857495

Post a Comment

emo-but-icon

item