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/