0

void swap(int *x,int *y)
{
static int *temp;
temp=x;
x=y;
y=temp;

}

void printab()
{
static int i,a=-3,b=-6;
i=0;
while(i<=4)
{
if((i++)%2==1) continue;
a=a+i;
b=b+i;


}
swap(&a,&b);
printf("a=%d b=%d out side rec\n",a,b);

}

main()
{
printab();
printf("end of output 1");
printab();

}

out put for the first printab() is 6 3 , i.e numbers are not getting swaped

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by srinath1
0

You are passing the pointer by value. And you are swapping the copy of the actual pointers in swap() function. When it comes out from the function, the pointers' copies go out of scope and hence no swap happens.

One solution is to pass the pointer by reference.

Other solution is to swap the values rather than swap the pointers (in swap() function) like shown below.

void swap(int *x,int *y)
{
    static int temp;
    temp=*x;
    *x=*y;
    *y=temp;
}

Edited by subith86: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.