0

I was going through a book about C and there's this "ANALYZE!" problem that I can't quite decipher/understand. It has this code presented:

void x(int *y, int *z)
{
    *y = *y ^ *z;
    *z = *y ^ *z;
    *y = *y ^ *z;
}  

After showing that, it asked for a better way to name the function than "x". After renaming the function, it said "Determine the role of this function to *y and *z."

The whole thing is kind of vague for me. What does the questions imply? Additionally, how can I understand and answer this?

thepajama
  • 55
  • 1
  • 9
  • 1
    It seems that your are asked to explain what the function does (swaps the contents of the passed addresses using XOR) then a better name for the function is `swap()` – David Ranieri Nov 15 '20 at 07:19
  • Note: the XOR operations must be written separately (as in your question) and not chained together, e.g. `*y ^ *z && *y ^= *z ^= *y ^= *z` See [Swapping Values with XOR](https://stackoverflow.com/questions/20842602/swapping-values-with-xor) (UB). – David C. Rankin Nov 15 '20 at 07:59

3 Answers3

3

The questions you are being asked about this function, basically, are "what is this function actually doing?", and "based on that, what would be an appropriate name for this function?"

"Determine the role of this function to *y and *z" seem to be an oddly worded question to me, I might word that as "what effect does this function have on the values *y and *z?".

This isn't my real name
  • 4,869
  • 3
  • 17
  • 30
3

Hint: express everything in terms of the original inputs to get the following equivalent code.

void x(int *y, int *z)
{
    int yy = *y, zz = *z;

    *z = (yy ^ zz) ^ zz;
    *y = (yy ^ zz) ^ ((yy ^ zz) ^ zz);
}

Then simplify the right-hand sides using that ^ is associative, commutative and a ^ a = 0.

dxiv
  • 16,984
  • 2
  • 27
  • 49
-1

The better name for this function is "swap".