Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Wednesday, 25 February 2015

Call by Value and Call by Reference

Passing Argument to Function :

  1. In C Programming we have different ways of parameter passing schemes such as Call by Value and Call by Reference.
  2. Function is good programming style in which we can write reusable code that can be called whenever require.
  3. Whenever we call a function then sequence of executable statements gets executed. We can pass some of the information to the function for processing calledargument.

Two Ways of Passing Argument to Function in C Language :

  1. Call by Reference
  2. Call by Value
Let us discuss different ways one by one –

A.Call by Value :

#include<stdio.h>

void 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 : Call by Value

  1. While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called function.
  2. Any update made inside method will not affect the original value of variable in calling function.
  3. 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.
  4. As their scope is limited to only function so they cannot alter the values inside main function.
Call by Value in C Programming Scheme

B.Call by Reference/Pointer/Address :

#include<stdio.h>

void 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 : Call by Address

  1. While passing parameter using call by address scheme , we are passing the actual address of the variable to the called function.
  2. Any updates made inside the called function will modify the original copy since we are directly modifying the content of the exact memory location.
Call by Pointer or Address or Reference in C Programming Scheme

Summary of Call By Value and Call By Reference :

PointCall by ValueCall by Reference
CopyDuplicate Copy of Original Parameter is PassedActual Copy of Original Parameter is Passed
ModificationNo effect on Original Parameter after modifying parameter in functionOriginal Parameter gets affected if value of parameter changed inside function