Parameter Passing

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 10

PARAMETER

PASSING
METHODS

TYPES
Parameter passing :Giving data's
from calling function to called
function .
Call by value
Passing copy of the variable

Call by reference
Passing address of the variable

CALL BY VALUE
While Passing Parameters using call by
value , xerox copy of original parameter
is created and passed to the called
function.
Any update made inside method will not
affect the original value of variable in
calling function.

Swapping two values using call


by value
#include<stdio.h>
void swap(int x,int y) ;
void main()
{
int a=50,b=70;
swap(a,b);
printf("\n a =%d,a);
printf("\n b=%d",b);
}

void swap(int x, int y)

{
int temp;
temp = x;
x = y;
y = temp;
}
Output
a= 50
b=70

In the above example a and b are the


original values and Xerox copy of these
values is passed to the function and these
values are copied into x,y variable of swap
function respectively.
As their scope is limited to only function so
they cannot alter the values inside main
function.

CALL BY REFERENCE
While passing parameter using call by
reference (or call by address) scheme , we
are passing the actual address of the
variable to the called function.
Any updates made inside the called
function will modify the original copy,
since we are directly modifying the content
of the exact memory location.

Swapping two values using call


by refernce
#include<stdio.h>
void swap(int *x,int *y) ;
void main()
{
int a=50,b=70;
swap(&a,&b);
printf("\n a =%d,a);
printf("\n b=%d",b);
}

void swap(int *x, int *y)


{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output
a= 70
b=50

In the above example a and b are the


actual values and address of these values
is passed to the swap function and these
address are copied into x,y pointer
variable of swap function respectively.
Any updates made inside the called
function are directly modifying the
content of the original copy.
Because it works with exact memory
location.

Call by value
#include <stdio.h>
void addvalue(int );
int main()
{
int a=10;
printf(\n a = %d before
function call", a);
addvalue(a);
printf(\n a = %d after
function call", a);
return 0;
}

void addvalue(int x)
{
x += 10;
printf(\n Inside addvalue
function , x = %d , x);
}
output
a = 10 before function call
Inside addvalue function x =20
a = 10 after function call.

Call by reference
#include <stdio.h>
void addvalue(int* );
int main()
{
int a=10;
printf(\n a = %d before
function call", a);
addvalue(&a);
printf(\n a = %d after
function call", a);
return 0;
}

void addvalue(int *x)


{
*x += 10;
printf(\n Inside addvalue
function , x = %d , *x);
}
output
a = 10 before function call
Inside addvalue function x =20
a = 20 after function call.

You might also like