2

The code below returns a reversed string. For example, it take input "codebyte" and returns "etybedoc".

string FirstReverse(string str) {
    for(int i = 0, j = str.length() - 1; i < str.length() / 2; i++, j--)
    {
        str[i]^=str[j]^=str[i]^=str[j];
    }
    return str;
}

I am lost as to how this function works:

  1. Why is the ^=-operator being used? It is a bitwise operator but why is it being used here?
  2. Why is str.length() divided by 2 in the for loop?
  3. What is with the alteration of str[i] and str[j]?

I want to work though it with values but I don't know where to begin. The introductory textbook I used did not cover this.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
VickTree
  • 889
  • 11
  • 26
  • 3
    It's a swapping functionality similar to the famous bit-twiddling hacks. The length is divided by two because otherwise you would undo every swap and end up with the original string again. – Thomas Lang Jan 27 '19 at 19:07
  • 3
    It's using XOR operator to swap the characters. https://en.wikipedia.org/wiki/XOR_swap_algorithm – Hitobat Jan 27 '19 at 19:09
  • 6
    I would flunk this code in code review. I'm not even sure it would work on every compiler as it seems like it might have the kind of order of evaluation dependency that the standard would say results in undefined behavior. – Omnifarious Jan 27 '19 at 19:09
  • 1
    Possible duplicate of [How does XOR variable swapping work?](https://stackoverflow.com/questions/249423/how-does-xor-variable-swapping-work) – UnholySheep Jan 27 '19 at 19:09
  • @Omnifarious Absolutely, this is code by someone who thinks they're being clever but ends up writing bad code. – john Jan 27 '19 at 19:10
  • 2
    The right way to write that expression with all the `^=` in it is `::std::swap(str[i], str[j]);` . – Omnifarious Jan 27 '19 at 19:15
  • Also the result of bitwise xor might produce a trap representation – M.M Jan 27 '19 at 19:58

1 Answers1

3

As an answer:

  • It's a swapping functionality similar to the famous bit-twiddling hacks.
    • A detailed explanation of this swapping mechanism can be found here.
  • The length is divided by two because otherwise you would undo every swap and end up with the original string again.
  • The indices i and j run against each other (from the beginning or end, respectively).
Thomas Lang
  • 770
  • 1
  • 7
  • 17
  • 1
    For this to be anything like a good answer, you should explain the bit-twiddling. –  Jan 27 '19 at 19:40