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?
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.
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.
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.
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.
There is no such operator, but this is a little bit shorter: booleanWithAVeryLongName ^= true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With