Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / Java: Toggle boolean statement?

Is there a short way to toggle a boolean?

With integers we can do operations like this:

int i = 4;
i *= 4; // equals 16
/* Which is equivalent to */
i = i * 4;

So is there also something for booleans (like the *= operator for ints)?

In C++:

bool booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?

In Java:

boolean booleanWithAVeryLongName = true;
booleanWithAVeryLongName = !booleanWithAVeryLongName;
// Can it shorter?
booleanWithAVeryLongName !=; // Or something?
like image 612
Martijn Courteaux Avatar asked Jun 18 '10 13:06

Martijn Courteaux


People also ask

How do you toggle a boolean?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.

Can you use a boolean in a switch statement Java?

The expression used in a switch statement must have an integral or boolean expression, or be of a class type in which the class has a single conversion function to an integral or boolean value. If the expression is not passed then the default value is true. You can have any number of case statements within a switch.

How do you flip a boolean value in Java?

Therefore, we can make use of XOR's characteristics, performing b ^ true to invert b's value: b = true -> b ^ true becomes true ^ true = false. b = false -> b ^ true becomes false ^ true = true.

How do you switch between true and false?

Method 1: Using the logical NOT operator: The logical NOT operator in Boolean algebra is used to negate an expression or value. Using this operator on a true value would return false and using it on a false value would return true. This property can be used to toggle a boolean value.


1 Answers

There is no such operator, but this is a little bit shorter: booleanWithAVeryLongName ^= true;

like image 143
Petar Minchev Avatar answered Oct 02 '22 17:10

Petar Minchev