翻转布尔值的最简单方法?

2022-01-19 00:00:00 c boolean boolean-logic c++

我只想根据它已经是什么来翻转一个布尔值.如果它是真的 - 让它成为假的.如果它是假的 - 让它成为真的.

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.

这是我的代码摘录:

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

推荐答案

你可以像这样翻转一个值:

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

相关文章