views:

280

answers:

3

If you have a boolean variable:

boolean myBool = true;

I could get the inverse of this with an if/else clause:

if (myBool == true)
 myBool = false;
else
 myBool = true;

Is there a more concise way to do this?

+28  A: 

Just assign using the logical NOT ! operator like you do in your condition statements (if, for, while...). You're working with a boolean value already, so it'll change true to false (and vice versa):

myBool = !myBool;
BoltClock
+8  A: 

An even cooler way:

myBool ^= true;

And by the way, don't use if (something == true), it's simpler if you just do if (something) (the same with comparing with false, use the negation operator).

fortran
Heck yeah XOR! +1
BoltClock
Those are the little things that make the endless hours of programming funnier xD
fortran
I was hoping to find a concise syntax that my coworkers will understand intuitively without needing to ask a question on StackOverflow to understand what I'm doing.
faq
You are not thinking in positive! Think about the enlightenment they will get after browsing SO for a while trying to understand what you were doing!!! :-p
fortran
You're right. Let's see what they think of our efforts to enlighten them.
faq
They will be delighted, I can tell you that! :-D
fortran
how about `myBool = (myBool == false);`?
Jorn
@Jorn good one too! :-D
fortran
@faq: You're completely missing the point! The goal of programming isn't to write programs that others can understand. It's to write programs that are so sophisticated that anyone reading it is instantly impressed with how smart you must have been to be able to write this. :)
Jay
@Jay or as a friend of mine would say: If it was hard to write, it should be hard to read! XD
fortran
A: 

myBool = myBool?false:true;

Jinjavajin
copied from the comments to the question?
Jorn
Is there no difference between both?
Jinjavajin
Is there no difference between both?
Jinjavajin
Is there no difference between both?
Jinjavajin