All you want is
if (condition)
value = !value;
No need to bring the conditional operator in; that would just be unnecessary clutter. The reason this would be preferable over
value = condition ? !value : value;
is because the above performs an assignment irrespective of condition
's value; if condition
is false
, we just assign value
to itself. This works as well, but isn't really what you want logically. You want to invert value
(i.e. perform an assignment) if condition
is true. I would argue that the the second variant is simply a misuse of the conditional operator. Beyond that, the first variant is certainly more readable and easier to follow.