Pages

Friday 22 February 2019

Program to illustrate Call By Value and Call By Reference

C provides two ways of passing arguments to a function.
 1. Call by value or Pass by value.
 2. Call by reference.

1. Call by value or Pass by value:
            In this method a copy of each of the actual arguments is made first then these values are assigned to the corresponding formal arguments.
            This means that the changes made by the called function have no effect on the values of actual arguments in the calling function.

Program to illustrate call by value or pass by value
#include<stdio.h>
#define pf printf
#define sf scanf
void cbv(int,int); // fuction declaration or prototype
void main()
{
 int a,b;
 pf("\n Enter a value :");
 sf("%d",&a);
 pf("\n Enter b value :");
 sf("%d",&b);
 pf("\n Initial values of a=%d and b=%d\n",a,b);
 pf("\n Calling the function \n");
 cbv(a,b);   // calling function
 pf("\n Final   values of a=%d and b=%d",a,b);
}

void cbv(int p,int q)  // called function
 {
  int temp;
  temp=p;
  p=q;
  q=temp;
  pf("\n Value of p (inside function) = %d\n ", p);
  pf("\n Value of q (inside function) = %d\n", q);
 }

output:


2. Call by reference :
To use call by reference we need to do two things:
 
1. Pass the addresses of the actual arguments instead of passing values to the function.
2. Declare the formal arguments of the function as pointer variables of an appropriate type.
Program to illustrate Call By Reference
#include<stdio.h>
#define pf printf
#define sf scanf
void cbr(int *,int *); // fuction declaration or prototype
void main()
{
 int a,b;
 pf("\n Enter a value :");
 sf("%d",&a);
 pf("\n Enter b value :");
 sf("%d",&b);
 pf("\n Initial values of a=%d and b=%d\n",a,b);
 pf("\n Calling the function \n");
 cbr(&a,&b);   // calling function
 pf("\n Final   values of a=%d and b=%d",a,b);
}

void cbr(int *p,int *q)  // called function
 {
  int temp;
  temp=*p;
  *p=*q;
  *q=temp;
  pf("\n Value of p (inside function) = %d\n ", *p);
  pf("\n Value of q (inside function) = %d\n", *q);
 }

output:

No comments:

Post a Comment

Programs in turboc3 : Files

File Handling in C File Handling concept in C language is used for store a data permanently in computer. Using this concept we can store our...