(a)
What
is calling by reference? How it is different from call by value?
Write a C function to swap two given
numbers using call by
reference mechanism.
If you are calling by reference it means
that compilator will not create a local copy of the variable which you are
referencing to. It will get access to the memory where the variable saved. When
you are doing any operations with a referenced variable you can change the
value of the variable.
Call
by value is where a copy of an object is placed in the parameter stack. The
called function can access and manipulate that copy at will, but it cannot
change the original copy because it has no way of knowing where that original
copy is located. Call by Reference, on the other hand, is where the address of
an object is placed in the parameter stack. Using extra syntax, the * or the
->, the called function can access and manipulate the original copy at will.
#include<stdio.h>
#include<conio.h>
void
swap(int *num1, int *num2);
void
main()
{
clrscr();
int
x,y;
printf(“Enter
the number: “);
scanf(“%d”,&x);
printf(“Enter
the number: “);
scanf(“%d”,&y);
printf(“x= %d y= %d \n”,x,y);
swap(&x,&y);
printf(“x=
%d y= %d”,x,y);
getch();
}
void
swap(int *num1, int *num2)
{
int
temp;
temp=*num1;
*num1=*num2;
*num2=temp;
}
No comments:
Post a Comment