Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to flip a boolean value?

People also ask

How do you invert a boolean value?

On the main or context menu, select Refactor | Invert Boolean. In the dialog that opens, specify the name for the inverted method or variable.

How do you make a boolean opposite?

The operator. not_() function takes a boolean value as its argument and returns the opposite of that value.

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.

How do you invert a boolean in Python?

Using the operator. not_() Function to Negate a Boolean Expression in Python. We can also negate the Boolean expression using a function named operator. not_().


You can flip a value like so:

myVal = !myVal;

so your code would shorten down to:

switch(wParam) {
    case VK_F11:
    flipVal = !flipVal;
    break;

    case VK_F12:
    otherVal = !otherVal;
    break;

    default:
    break;
}

Clearly you need a factory pattern!

KeyFactory keyFactory = new KeyFactory();
KeyObj keyObj = keyFactory.getKeyObj(wParam);
keyObj.doStuff();


class VK_F11 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class VK_F12 extends KeyObj {
   boolean val;
   public void doStuff() {
      val = !val;
   }
}

class KeyFactory {
   public KeyObj getKeyObj(int param) {
      switch(param) {
         case VK_F11:
            return new VK_F11();
         case VK_F12:
            return new VK_F12();
      }
      throw new KeyNotFoundException("Key " + param + " was not found!");
   }
}

:D

</sarcasm>

Easiest solution that I found:

x ^= true;

If you know the values are 0 or 1, you could do flipval ^= 1.


Just for information - if instead of an integer your required field is a single bit within a larger type, use the 'xor' operator instead:

int flags;

int flag_a = 0x01;
int flag_b = 0x02;
int flag_c = 0x04;

/* I want to flip 'flag_b' without touching 'flag_a' or 'flag_c' */
flags ^= flag_b;

/* I want to set 'flag_b' */
flags |= flag_b;

/* I want to clear (or 'reset') 'flag_b' */
flags &= ~flag_b;

/* I want to test 'flag_b' */
bool b_is_set = (flags & flag_b) != 0;