tags:

views:

1631

answers:

13

I've seen this before in code, but forgotten it. Basically it toggles a boolean variable. If it's true, it'll set to false and vice-versa. But unfortunately forgot the syntax.

It's basically a one liner for this:

if (myVar) {  
    myVar = false;  
} else {  
    myVar = true;  
}  

It's something like this, but don't know what it's called or the correct syntax of it:

myVar = myVar : false ? true;
+60  A: 

How about

myVar = !myVar

?

Alexander Rautenberg
this is simpler IMO
Gabriel
Yeah, this is a good toggle -- although it really depends on what you are doing in your app whether you want to use a given syntax for something like this. You know -- how conceptually close it is to what you're actually doing.
Joshua Evensen
+0: Because this answer only offers an alternative, it doesn't answer the question at all.
Guffa
you got almost all of your rep from this, didn't you? This is why I don't write answers.
Vuntic
`myVar = !!!myVar`
irreputable
This is insanity, +40 for an answer that doesn't even mention the conditional operator half of the question?
Michael Mrozek
Works and is simple. I guess I forgot 5th grade math :P
dime
I saw this syntax a while ago and I was just amazed at it's simplicity.
Litso
+25  A: 

myVar = myVar ? false : true; is using the conditional operator.

You can just do this though

myVar = !myVar;
nos
You have the : and ? backwards. It goes `condition ? true branch : false branch`.
Tesserex
@Tesserex: fixed
Jonathan Fingland
Also, this is frequently referred to as "the ternary operator" due to the fact that it is the only 3-arity operator in most programming languages.
Ben
+4  A: 

The smallest code I can think of at the moment. I don't know what its called (if it has a name, as you seem to suggest)

myVar = !myVar
Goutham
It is called a *negation*. There should be a list of arithmetic and logical operators in the manual somewhere.
Alexander Rautenberg
Unary negation?
Mark Canlas
Are there any others?
Alexander Rautenberg
The operation is negation operation of course but I naively thought the expression as a whole might have some other fancy name in popular lingo.
Goutham
+5  A: 

What you are thinking of is the conditional operator:

myVar = myVvar ? false : true;

(As you see, a lot of people call this "the ternary operator", but that only means that it is an operator with three operands. As it happens, there is only one operator with three operands in this language, but it still says nothing about what the operator does.)

It's of course easier to use the negation operator:

myVar = !myVar;
Guffa
A: 

There is a ternary operator (wikipedia). Which allows you to write a condensed if-else statement like in the second example.

In java:

myVar = (myVar) ? true : false;

There is also the NOT operator, which toggles a boolean variable. In java that is !. I believe that is what you want.

myVar = !myVar;
dnephin
+4  A: 

What you're talking about is the "ternary" or "conditional" operator, which does an inline substitution as per a condition.

The syntax is:

condition ? trueValue : falseValue

I usually throw parentheses around my condition, sometimes around the whole conditional operator. Depends on how much I'm trying to delineate it from everything else.

So for example, suppose you want to return the larger of two numbers:

public int max(int a, int b)
{
  return (a > b) ? a : b;
}

Notice that it can be substituted into the middle of something else.


Okay, now let's tackle your actual question about toggling a boolean type.

myVar = (myVar) ? false : true;

is how you would do it with the conditional operator. (Again, parentheses aren't required, I just favor them.)

But there's a simpler way to toggle the boolean... using the logical NOT ("!") operator:

myVar = !myVar;

Keep it simple. :-)

Platinum Azure
+3  A: 
if(myVar == true)
{
    myVar = false;
}
else if (myVar == false)
{
    myVar = true;
}
else
{
    myVar = FILE_NOT_FOUND
}
Visage
-1 and a groan for the typo (myVar vs MyVar) and for overly verbose, +1 for the humor at the end. Fix the typo and I might give you +1 (and a groan). :-)
Platinum Azure
No upvote from me because I don't want to confuse anyone seriously looking for this info, but you get my upvote in spirit. :)
Jeff
-1 for being intentionally misleading
Erick Robertson
Citation: http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
Rob Hruska
+1 for being intentionally misleading.
Chris Lively
-1. Keep bad and completely obvious TheDailyWTF references to the bad and completely obvious TheDailyWTF comment sections.
Mark Peters
+1  A: 

This also works :P

v=v?!v:!v;
OscarRyz
Love this one!!! But to keep it in the Java spirit it should probably bev = (!v == false) ? !v : !v
Alexander Rautenberg
Hahahahaha! That's brilliant. Too condensed for Java, though-- that could actually win a code golf! :-P
Platinum Azure
What about: `v=!v?!v:!v;` :) :)
OscarRyz
@Oscar: brilliant and for added unreadability call the variable `i`: `i=!i?!i:!i;`.
Joachim Sauer
@Joachim, ehehh or it lowercase "L" `l=!l?!l:!l;`
OscarRyz
A: 
public boolean toggle(boolean bool)
{
  return !bool;
}
baklap
+1 for being a good sport and letting me edit. Sorry :-)
Platinum Azure
I won't downvote, but the idea of having a helper function for this makes me die a little inside. It would be like having a function `public int plus(int a, int b) { return a + b };`. Just adding redundancy. It might have merit if Java had pass-by-ref.
Mark Peters
+15  A: 

Another option is XOR:

myVar ^= true;

It's notable in that only the LHS of the assignment ever changes; the right side is constant and will toggle any boolean variable. Negation's more self-documenting IMO, though.

Mark Peters
Given a variable name with length > 4, this will also be the shortest code you can find.
Mark Peters
It is also faster than anything else (not that you should be worried about speed at this level).
ILMTitan
you can make it even shorter: `myVar ^= 1;`
Lie Ryan
@Lie: The OP asked about Java. That's not valid for a Java boolean.
Mark Peters
Can somebody comment as to the downvotes? I know it's functionally correct, that's not very difficult to prove. So I'm not sure why it's gotten downvoted twice.
Mark Peters
myVar^=1>0; Given a variable name with length > 3, is *this* the shortest code you can find?
Thomas Mueller
In Java, it's actually not faster than myVar = !myVar; according to my test
Thomas Mueller
OK Thomas, I stand corrected :-). Well golfed. I suppose you could also have a constant `public static final boolean T = true` that would allow `myVar^=T;` That would amortize to less code.
Mark Peters
A: 

As you requested a trick I would offer this one:

myVar ^= true;
Moritz
A: 

As others have noted, there are two ways to negate something: "lvalue = !lvalue;" and "lvalue ^= 1;". It's important to recognize the differences.

Saying "lvalue = !lvalue" will cause lvalue to be set to 1 if it was zero, and 0 if it was set to anything else. The lvalue will be evaluated twice; this is not a factor for simple variables, but saying "someArray[index1][index2][index3][index4] = !someArray[index1][index2][index3][index4]" could slow things down.

Saying "lvalue ^= 1;" will cause lvalue to be set to 1 if it was 0, 0 if it was 1, and something else if it was neither zero nor 1. The lvalue need only be specified or evaluated once, and if the value is known to be either zero or 1, this form is likely to be faster.

Too bad there's no auto-negate operator; there are times such a thing would be handy.

supercat
It's a Java question. 1 won't work.
EJP
A: 

You can also use the binary form of negation as shown here.

if ((v == true) && !(v = false)) {
    v != true;   /* negate with true if true. */
} else {
    v =! false;  /* negate with false if false. */
}
kbob
I wish I could downvote this multiple times. I can only think this wasn't posted in good faith, it's so wrong. I guess for starters I could say `!=` is not an assignment operator, so `v != true;` won't change v.
Mark Peters
Agreed. Is this a joke?
EJP