Call by Value

In many functions, we passed arguments to them, but if we observe carefully, we will see that we have always created new variables for arguments in the function and then passed the values of actual arguments to them. Such function calls are called “call by value”.

Let us illustrate the above concept in more detail by taking a simple function of multiplying two numbers:

Write a program to multiply the two given numbers

#include <stdio.h>
main()
{
int x, y, z;
int mul(int, int);
printf (“Enter two numbers: \n”);
scanf (“%d %d”,&x,&y);
z= mul(x, y); /* function call by value */
printf (“\n The product of the two numbers is : %d”, z);
}
/* Function to multiply two numbers */
int mul(int a, int b)
{
int c;
c =a*b;
return(c);
}

OUTPUT

Enter two numbers:
23 2
The product of two numbers is: 46

Now let us see what happens to the actual and formal arguments in memory.

call by value
call by value

What is meant by local variables? The answer is local variables are those which can be used only by that function

Advantages of Call by value:

The only advantage is that this mechanism is simple and it reduces confusion and complexity.

Disadvantages of Call by value:

As you have seen in the above example, there is separate memory allocation for each of the variable, so unnecessary utilization of memory takes place.

The second disadvantage, which is very important from the programming point of view, is that any changes made in the arguments are not reflected to the calling function, as these arguments are local to the called function and are destroyed with function return.

Let us discuss the second disadvantage more clearly using one example:

Write a program to swap two values.

The variables are local to the mul ( ) function which is created in memory with the function call and is destroyed with the return to the called function

/*Program to swap two values*/
#include <stdio.h>
main ( )
{
int x = 2, y = 3;
void swap(int, int);
printf (“\n Values before swapping are %d %d”, x, y);
swap (x, y);
printf (“\n Values after swapping are %d %d”, x, y);
}
/* Function to swap(interchange) two values */
void swap( int a, int b )
{
int t;
t = a;
a = b;
b = t;
}

OUTPUT

Values before swap are 2 3
Values after swap are 2 3

But the output should have been 3 2. So what happened?

Here we observe that the changes which take place in argument variables are not reflected in the main() function; as these variables, namely a, b and t will be destroyed with function return.

• All these disadvantages will be removed by using “call by reference”.

 

Leave a Reply

Your email address will not be published.

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

%d bloggers like this: