The mechanism used to convey information to the function is the arguments or parameters. When values are passed to the function via actual arguments, the value of the actual argument is copied in to the formal argument. Therefore, the changes made to the formal argument have no effect on the actual argument. This procedure of passing the value of the argument to a function is known as call by value. Figure illustrates the concept of parameter passing mechanism.
Call – by – value mechanism does not change the content of the arguments in the calling function even if they are changed in the called function. The formal parameters are stored in the local data area of the called function. So the changes to the formal parameter within the function will effect only the local copy, and will have no effect on the actual argument.
Function accesses arguments by using the argument names in the function header. The actual and formal arguments should match in number, type and order. The values of actual arguments are assigned to the formal arguments on a one to one basis, starting with the first argument. The program segment illustrates this.
int box _area (int, int); /* prototype */
void main ()
{
int length = 7, area;
area = box_ area (length, 15);
. . . .
}
int box _ area (int l, int w)
{
int a;
a = l * w;
return a;
}
in the above program segment, length is mapped to l and 15 is mapped to w in the box _ area function. Passing an argument by values has advantages and disadvantages. The advantages are that it allows a single – valued arguments to be written as an expression, rather than being restricted to a single variable. Furthermore, in cases where the argument is a variable, the value of this variable is protected from alterations which take place within the function. The main disadvantage is that information cannot be transferred back to the calling portion of the program via arguments. In other words, passing by value is a strictly one – way method of transferring information.
Program – Find out the largest of 2 numbers
#include<stdio.h>
void main ()
{
int x, y, max;
int large (int, int);
printf (“Enter the first number: “);
scanf (“%d”, &y);
printf (“\nEnter the second number:”);
scanf (“%d”, &y);
max = large (x, y);
printf (“\nLargest of %d and %d is %d”, x, y, max);
}
int large (int a, int b)
{
int large (int a, int b)
c = (a>= b)? a: b;
return c;
}
Output
Enter the first number: 23
Enter the second number: 12
Largest of 23 and 12 is 23
About the Author
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc