Graywd - 4 months ago 36

C++ Question

I typed these code. However, the output is beyond my expectations.

`#define SWAP(x,y) {x=x^y;y=x^y;x=x^y;}`

#define SWAP2(x,y) {x=x+y;y=x-y;x=x-y;}

int main()

{

int ia[] = { 1, 10, 1 };

SWAP(ia[0], ia[0]); // the resutl is ia[0] = 0

SWAP(ia[1], ia[2]); // work fine

SWAP2(ia[1], ia[1]) // the result is ia[0] = 0

}

Anyone can help me? Any help will be appreciated.

Answer

Your problem is that your swap algorithms *require* the two arguments to be *separate* pieces of memory.

As noted by LYF_HKN, the first step in each algorithm causes `x`

to become 0 when `x=y`

. If the two are merely *equal* but are still *separate* pieces of memory, this is fine, because the second step will leave `y`

unchanged (because `x`

is 0), and the third step will restore the original value of `x`

*if* `y`

is now equal to that original value.

However, when `x`

and `y`

are actually the *same* object in memory, then the first operation in each algorithm, in setting `x`

to 0, *also* sets `y`

to 0, since `y`

*is* `x`

. Thus the rest of each algorithm merely preserves the value 0 in this memory space.