Easiest way to flip a boolean value?

John T picture John T · Mar 4, 2009 · Viewed 209k times · Source

I just want to flip a boolean based on what it already is. If it's true - make it false. If it's false - make it true.

Here is my code excerpt:

switch(wParam) {

case VK_F11:
  if (flipVal == true) {
     flipVal = false;
  } else {
    flipVal = true;
  }
break;

case VK_F12:
  if (otherVal == true) {
     otherValVal = false;
  } else {
    otherVal = true;
  }
break;

default:
break;
}

Answer

John T picture John T · Mar 4, 2009

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;
}