Header Ads Widget

Passing individual array elements to a function (Call by value and Call by reference) in C

 Array elements can be passed to a function by calling  the function by value or by reference.

Call by value : Consider a program-

#include <stdio.h>

void show( int );

int main()

{

    int i;

    int num [] ={5,6,44,3,8};

    for(i=0; i<5; i++)

    {

     printf(" \n  Element  %d of array=",(i+1));

     show( num[i]);

    }

    return 0;

}

void show( int x)

{

     printf("%d \t", x++);

}

Here we are passing an individual array element at a time to function show() and getting it printed in the function show(). In this method, changes made to the formal argument has no effect on value of actual argument.

Call by reference : Consider a program -

#include <stdio.h>

void show( int * );

int main()

{

    int i;

    int num [] ={5,6,44,3,8};

    printf("Original elements of array: \n");

    for(i=0; i<5; i++)

    {

        show( &num[i]);

    }

    printf("\n Impact of modification (* x)++ : \n");

    for(i=0; i<5; i++)

    {

        printf("%d \t",num[i] );

    }

    return 0;

}

void show( int *x)

{

     printf("%d \t", (*x)++);

}

Here we are passing addresses of individual array elements to the function show(). Since x contains address so it is  declared as pointer variable and to print array elements we are using the value at address operator (* ).  Using formal arguments we can make changes in actual arguments of calling function.

Post a Comment

1 Comments