# How can I swap two values and return two integers?

I wanted to write a function that swaps two values, but I'm not sure how to return 2 integers. This code doesn't work, as after swapping the values x is still one and y is still 2:

``````void swap(int in_1, int in_2);

int main(void)
{
int x = 1;
int y = 2;
printf("x = %d\n", x);
printf("y = %d\n", y);
printf("swapping...\n");
swap(x,y);
printf("x = %d\n", x);
printf("y = %d\n", y);
}

void swap(int in_1, int in_2)
{
int temp = in_1;
in_1 = in_2;
in_2 = temp;
return;
}
``````
• I know that the function only swaps values inside, but how would you program this to actually swap x and y? Aug 8, 2014 at 13:16

This exact problem is reviewed in the lectures. In short, you have to use pointers in your swap function. I'm pretty sure it's week 4, 2nd lecture (lecture continued). Or you can check out the lecture notes here: http://d2o9nyf4hwsci4.cloudfront.net/2013/fall/lectures/4/w/notes4w/notes4w.html

``````    void swap(int* a, int* b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
``````
• Ah thanks!! Still at pset3 for now :) Aug 8, 2014 at 13:37

You are not required to return the two values, what your swap() function is doing is going to where the numbers are stored and subsequently changing them.

*a means go to where a is

so

temp = *a is take the value from a and store it in temp

*a = *b is take the value from b and store it where a is

this means you don't have to return anything out of your swap function.

The flipside is you need to pass pointers (int*) into the swap() function instead of just two ints.

• Ah thank you!!! Aug 8, 2014 at 13:37