Computer Science, asked by stepup01, 1 year ago

write a program to explain the concept of call by value and call by reference?

Answers

Answered by sushiladevi4418
2

Explanation:

Call by value:

  • The value of the actual parameter is passed to the formal parameter which means the value of the variable is used.
  • In which the coder does not modify the value of the actual parameter.
  • Separate memory is allocated to the actual and formal parameters.

Program:

#include<stdio.h>  

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);  

}  

int main() {  

int x=100;  

printf("Before function call x=%d \n", x);  

change(x);//passing value in function  

printf("After function call x=%d \n", x);  

return 0;  

}  

Output:

Before function call x=100  

Before adding value inside function num=100  

After adding value inside function num=200  

After function call x=100

Call by reference:

  • In which the address of the variable is passed as an actual parameter.
  • The actual parameter can be modified by the formal parameter.
  • The same memory is shared among both the formal and actual parameters.

Program:

#include<stdio.h>  

void change(int *num) {  

printf("Before adding value inside function num=%d \n",*num);  

(*num) += 100;  

printf("After adding value inside function num=%d \n", *num);  

}  

int main() {  

int x=100;  

printf("Before function call x=%d \n", x);  

change(&x);//passing reference in function  

printf("After function call x=%d \n", x);  

return 0;  

}

Output:

Before function call x=100  

Before adding value inside function num=100  

After adding value inside function num=200  

After function call x=200

Similar questions