say I have something like the following
How does having a temp variable allow for anything to safely swap with itself? I don't see it.Code:void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; }
say I have something like the following
How does having a temp variable allow for anything to safely swap with itself? I don't see it.Code:void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; }
Last edited by Overworked_PhD; 07-04-2008 at 06:29 PM.
I assume you meant y to be an int *.
I'm not sure how much more clearer this can be. temp takes on the value of x. x then takes on the value of y. Finally y takes on the old value of x, stored in temp.
What are you having trouble with?
Imagine you have 3 jars, one empty, one with a spider in it and one with a grasshopper in it.
You want to swap the spider and the grasshopper (ie they move jars), but they can't go in the same jar together else they'll kill each other. So instead you move the spider to the 3rd emtpy jar, and move the grasshopper into the spider's jar, and the spider into the grasshopper's jar. It doesn't matter if they're both spiders either, they still can't go in the same jar at the same time.
Like any variable in C... yes
Of course you could get techincal and argue that, but it will still only have one value, but how you interperate this value is another story. Laymans terms, 5678 you could argue from a programming point of view that 56 and 78 are two values that exist in one variable (and thus unpack them into other variables).
It really doesn't matter if the values are the same when you swap, it makes no difference at all.