1. 25

  2. 3

    Be careful when XOR-swapping two integers that are addressed by pointers/references. If they both point to the same memory location, then the value gets erased to zero. In C it would be good to add the restrict keyword to the two pointers, to let the human know about this pitfall (it doesn’t stop the compiler).

    1. 6

      Be careful when using coding tricks in production code.

      I doubt whether there’s still a compiler used “for real” which doesn’t optimize the normal swap algorithm, using a temporary variable, into whatever’s most efficient for the system, which usually works out to being a single opcode. This is decades-old peephole optimization stuff. The intricacies of restrict and pointer aliasing are useful to keep in mind in general, but if you’re using this trick in code where correctness matters, just use a temporary variable and have some faith in the people who wrote the optimizer.

    2. 3

      This is brilliant.

      1. 2

        Nice idea. But at first it was confusing to me, as I was expecting the foreground objects to represent 1. (The circle and square are black, but black is zero and white (the background) is one.)