954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

static

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

srinath1
Newbie Poster
11 posts since Jan 2012
Reputation Points: 10
Solved Threads: 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;
}
subith86
Junior Poster
124 posts since Mar 2011
Reputation Points: 30
Solved Threads: 14
 

thank you for the help .

srinath1
Newbie Poster
11 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You