Computer Programming C Laboratory: Functions C Programs

Interchanging two values (Call by reference)

Call by reference - Parameter Passing Methods - C Programming

Interchanging two values.

 /* Program to interchanging two values */

#include <stdio.h>

void interchange (int *a,int *b); /* Prototype declaration */

void main()

{

/* Local definition */

int i=5,j=10;

/* Statements */

clrscr();

printf("i and j values before interchange: %d %d\n",i,j);

interchange(&i,&j); /* pass address to function */

printf("i and j values after interchange : %d %d\n",i,j);

printf("i and j values after interchange in the main(): %d %d\n",i,j);

getch();

} /* main */

void interchange(int *a, int *b)

{

int t;

t=*a;

*a= *b;

*b=t;

} /* interchange */

OUTPUT

i and j values before interchange: 5 10

i and j values after interchange : 10 5

i and j values after interchange in the main(): 10 5

EXPLANATION: In this example, the variables i and j are assigned to values 5 and 0 respectively, then the interchange() function is called with the address of i and j and it interchanges the i and j values. In the program, we are passing addresses of formal arguments to the interchange() function. The pointers in the interchange() function operate on the actual argument through the pointer. So the changes made in the values are permanent.

 

Computer Programming C Laboratory: Functions C Programs : Tag: C Programming : - Interchanging two values (Call by reference)


Computer Programming C Laboratory: Functions C Programs



Under Subject



Related Subjects