0
2.4kviews
Explain the difference between call by value and call by reference with example.

Mumbai University> FE > Sem 2> STRUCTURED PROGRAMMING APPROACH

Marks: 8 M

Year: Dec 2016

1 Answer
1
1views
Call by value Call by reference
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
Actual and formal arguments will be created in different memory location. Actual and formal arguments will be created in same memory location.
Changes made inside the function is not reflected on other functions. Changes made inside the function is not reflected outside the function also.
A copy of value is passed to the function. An address of value is passes to the function.

Call by value Example:

#include<stdio.h>
#include<conio.h>
void change(int num);
main()
{
int x=50;
printf(“Before function call x=%d\n”,x);
change(x);
printf(“After function call x=%d\n”,x);
getch();
}

void change(int num)
{
printf(“Before adding value inside function num=%d\n”,num);
num=num+100;
printf(“After adding value inside function num=%d\n”,num);
}

Output:
Before function call x=50;
Before adding value inside function num=50
After adding value inside function num=150
After function call x=50

Call by reference Example:

#include<stdio.h>
#include<conio.h>
void change(int *num);
main()
{
int x=50;
printf(“Before function call x=%d\n”,x);
change(x);
printf(“After function call x=%d\n”,x);
getch();
}

void change(int *num)
{
printf(“Before adding value inside function num=%d\n”,*num);
*num=(*num)+100;
printf(“After adding value inside function num=%d\n”,*num);
}

Output:
Before function call x=50;
Before adding value inside function num=50
After adding value inside function num=150
After function call x=150
Please log in to add an answer.

Continue reading...

The best way to discover useful content is by searching it.

Search