0
1.3kviews
Explain the difference in using call by reference and call by value methods for argument passing, for swapping 2 numbers.
1 Answer
0
9views

Passing Argument to Function:

  • In C Programming we have different ways of parameter passing schemes such as Call by Value and Call by Reference.

  • Function is good programming style in which we can write reusable code that can be called whenever require.

  • Whenever we call a function then sequence of executable statements gets executed. We can pass some of the information to the function for processing called argument.

Call by Value:

Program Code:

#include<stdio.h>
int interchange(int number1,int number2){
int temp;
temp = number1;
    number1 = number2;
    number2 = temp;
}
int main() {
int num1=50,num2=70;
interchange(num1,num2);

printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}

Output:

Number 1: 50

Number 2: 70

Explanation:

  • 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.

  • In the above example num1 and num2 are the original values and xerox copy of these values is passed to the function and these values are copied into number1,number2 variable of sum function respectively.

  • As their scope is limited to only function so they cannot alter the values inside main function.

Call by Reference:

Program Code:

#include<stdio.h>
int interchange(int *num1,int *num2){
int temp;
temp  = *num1;
*num1 = *num2;
*num2 = temp;
}
int main() {
int num1=50,num2=70;
interchange(&num1,&num2);

printf("\nNumber 1 : %d",num1);
printf("\nNumber 2 : %d",num2);
return(0);
}

Output:

Number 1: 70

Number 2: 50

Explanation:

  • While passing parameter using 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.

Please log in to add an answer.