c++cbooleanboolean-logic

Easiest way to flip a boolean value?


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

Solution

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