Call by Value & Call by Reference by G Krishna Chauhan

There are two ways that a C function can be called from a program. They are,

Call by value
Call by reference


1. CALL BY VALUE:

In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.

Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):

In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.


#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);          

int main()
{
    int m = 22, n = 44;
    // calling swap function by value
    printf(" values before swap  m = %d \nand n = %d", m, n);
    swap(m, n);                         
}

void swap(int a, int b)

    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}


OUTPUT:

values before swap m = 22
and n = 44
values after swap m = 44
and n = 22


2. CALL BY REFERENCE:

In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.

EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):

In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.


#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b); 
 int main()
{
    int m = 22, n = 44;
    //  calling swap function by reference
    printf("values before swap m = %d \n and n = %d",m,n);
    swap(&m, &n);         
}

void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

OUTPUT:

values before swap m = 22
and n = 44
values after swap a = 44
and b = 22


No comments:

Post a Comment