This code is written to return swapped values, why values are not being returned, My basic question is how can i take return value from function called, please demonstrate with any code example.

int swap (int x,int y);
int main (void)
    int a = 1;
    int b = 2;
    printf("value of a and b is %i,%i respectively\n", a,b);
    printf ("Swapping!\n");
    swap (a,b);
   printf("value of a and b is %i,%i respectively\n", a,b);


int swap (int x,int y) { int temp=x; x=y; y=temp;

return x,y;


1 Answer 1


When you call swap() with int a and int b you are not actually "passing" swap() the variables. Instead you are handing swap() a copy of them, more specifically a copy of the value the variables contain. So you are indeed swapping correctly, you are just not handing over the final results back over the the caller. Below is a correct swap function.

void swap(int* first, int* second)
    int temp = *first;
    *first = *second;
    *second = temp;

Here you can see I prefixed the variable with a "*", this basically means the variable is a pointer (or an address) to a value, so now it refers to int a and int b. In other words, using this code, main() calls swap() with the address of its very own int a and int b.

Do keep in mind though, now that you're passing by reference. Is to call swap() like: swap(&a, &b);, the & or "address-of" operator retrieves the address of its right operand before passing it to swap().

CS50 covers this (pointers) in great detail -- in fact I'd say it is the primary focus of the course's middle-half -- more information is freely available all over the internet and at https://study.cs50.net/

  • Thanks a lot I got it....
    – Ahmed Raza
    Sep 28, 2016 at 11:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .