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

Recommended Answers

All 2 Replies

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;
}

thank you for the help .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.