Pages

January 22, 2013

Call by Value and Reference


call by value and call by reference function banner

CALL BY VALUE

When a function is called by value, the value of actual arguments is copy to the former arguments in the called function. The value may be altered but when the control is transferred back to calling function the altered value are not transferred back.

/* Program to show use of call by value function */

#include<stdio.h>
#include<conio.h>
int change(int i)
{
     i=i*5;
     printf("\n inside change is %d",i);
     return i;
     }
void main()
{
     int a,b,c,d;
     printf("\n enter any value of a and b");
     scanf("%d%d",&a,&b);
     c=a+b;
     printf("\n before change is %d",c);
     d=change(a);
     printf("\n after change is %d",c);
     getch();
     }

output of program to show use of call by value showing its scope in C language

CALL BY REFERENCE:

When function is called by reference the address of actual arguments is copied onto the former arguments. The content of the variable that are altered within the called function block returned to the calling function in the altered form itself because the actual and former arguments are referring the same memory location.

/*Program to show use of call by reference function*/

#include<stdio.h>
#include<conio.h>
void change( int *p)
{
     *p=*p+1;
     printf("\n inside change  is %d",*p);
     }
void main()
{
     int a;
     printf("\n enter any value of a");
     scanf("%d",&a);
     printf("\n before change is %d",a);
     change(&a);
     printf("\n after change is %d",a);
     getch();
     }
output of program to show use of call by reference using addition in C language

/*Program to show change in values by call by reference function*/

#include<stdio.h>
#include<conio.h>
void change(int *p)
{
     *p=*p*3;
     printf("\n inside change is %d",*p);
     }
void main()
{
     int a,b,sum;
     printf("\n enter any value of a and b");
     scanf("%d%d",&a,&b);
     sum=a+b;
     printf("\n before change sum is %d",sum);
     change(&sum);
     printf("\n after change sum is %d",sum);
     getch();
     }
output of program to show use of call by reference of arithmetic operators in C language

No comments:

Post a Comment