6

What is the most condense way to invert a boolean if another boolean is true. In other words, what is the shortest way of writing condition ? !value : value, preferably evaluating value only once?

Edit: Just so you know, I am passing the result to a method

Saucy Goat
  • 1,587
  • 1
  • 11
  • 32
BrainStorm.exe
  • 1,565
  • 3
  • 23
  • 40

7 Answers7

14

The shortest way is

value ^= condition;
Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
6

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
3

You could try:

value = condition ^ value

Not the most readible solution though.

zakinster
  • 10,508
  • 1
  • 41
  • 52
2

Is this what are you looking for?

if(condition)
   value = !value
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

Why would you even bother about the short or long even. Prefer more readable code. You can write

if (SomeCondition) {
    value = !value;
}

Since there is no need for else condition, since the value is value in else.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

as your question says 'invert bool if true'

you should use:

 if(statement)
    {

    value=!value;
    }
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49
  • With `if(statement==true)` you can easy make mistake by writing it like `if(statement=true)`. To avoid this kind of mistakes it is better to use [yoda conditions](http://en.wikipedia.org/wiki/Yoda_conditions): `if (true==statement)` or just `if(statement)` since `statement==true` is the same as just `statement`. – Pshemo Jan 06 '14 at 20:26
  • @Pshemo; Like Yoda conditions, I do. – Craig Tullis Mar 14 '14 at 22:25
0

A good way is to have a function or method like this

boolean invert(boolean condition, boolean value){ return condition != value; }

In fact:

condition value  inversion
t           t      f
t           f      t
f           t      t
f           f      f

in the first 2 cases condition is true and inversion is performed, otherwise in the last two cases.