Search code examples
language-agnosticlogical-operators

XOR or NOT for negation of a variable


I was wandering what is better/preferred practice while performing negation of a boolean variable, XOR or NOT?

bool someVariable;

I even don't know why, but I always use XOR, I just like it more:

someVariable ^= true;

However, the more obvious way is to use NOT:

someVariable = !someVariable;

I am probably using the first way so I don't need to type the name of a variable twice, reducing possibility of some errors, typos, etc. It is also less characters to type if the variable is longer than a few chars :)

However, the first way is not really obvious on the first look for anybody who do not use this trick.

Also, the XOR is IMHO more readable because you are sure that the negation is applied on the variable. The NOT could be with two different variables and it is easy to miss if the names look similar:

affect = !effect;

What are advantages and disadvantages of those two approaches? What should I use? Or it is only matter of personal preference?


Solution

  • Semantics

    Always go for semantically reasonable code. someVariable ^= true; is correct for sure, but might require thinking what it does (and why) to readers unused to this version of negating.

    someVariable = !someVariable; is very explicit about what it is doing: it negates someVariable without any possibility nor requirement to interpret it.

    Further Effects

    Furthermore it might be that some code analysis software can do whatever it might be able to (optimization, error analysis, ...) with the !-version, but fail at the rather unexpected ^-statement. During compilation, it might happen that the XOR-version is slower as (depending on the platform) can require to load true into another register before performing the operation. This effect is negligible in probably all cases, but the additional register used might be not.