i was assigned in my programming class to make a function of the form int swap(&a, &b) that doesnt use a third variable in the swap. i have pondered on this for a few hours and i cant think of anything. any help would appreciated. thanks in advance
Printable View
i was assigned in my programming class to make a function of the form int swap(&a, &b) that doesnt use a third variable in the swap. i have pondered on this for a few hours and i cant think of anything. any help would appreciated. thanks in advance
You can do this using bit manipulation, XOR-ing the values. I've
never needed to do this, but I believe it's something like:
a^=b;
b^=a;
a^=b;
Something like that.
Quzah.
>Something like that.
Yea, it's a common trick. There's no way to use it correctly, despite what some will tell you. Use a temporary variable, is it really that much harder?
Bad Practice:
a^=b;
b^=a;
a^=b;
Good Practice
temp = a;
a = b;
b = temp;
Seems just as easy to me, and you don't suffer scary code syndrome.
-Prelude
yeah I've seen this way, but it doesn't always work..
a^=b^=a^=b;
here's another way (simply mathematical)
a += b;
b = a - b;
a -= b;
>yeah I've seen this way, but it doesn't always work..
>a^=b^=a^=b;
Of course not, the value of each variable is modified more than once between sequence points, which results in undefined behavior.
-Prelude