[c++] 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;
}

This question is related to c++ c boolean boolean-logic

The answer is


Just because my favorite odd ball way to toggle a bool is not listed...

bool x = true;
x = x == false;

works too. :)

(yes the x = !x; is clearer and easier to read)


I prefer John T's solution, but if you want to go all code-golfy, your statement logically reduces to this:

//if key is down, toggle the boolean, else leave it alone.
flipVal = ((wParam==VK_F11) && !flipVal) || (!(wParam==VK_F11) && flipVal);
if(wParam==VK_F11) Break;

//if key is down, toggle the boolean, else leave it alone.
otherVal = ((wParam==VK_F12) && !otherVal) || (!(wParam==VK_F12) && otherVal);
if(wParam==VK_F12) Break;

Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:

template<typename T>    bool Flip(const T& t);

You can then specialize this for different types that might pretend to be boolean. For example:

template<>  bool Flip<bool>(const bool& b)  { return !b; }
template<>  bool Flip<int>(const int& i)    { return !(i == 0); }

An example of using this construct:

if(Flip(false))  { printf("flipped false\n"); }
if(!Flip(true))  { printf("flipped true\n"); }

if(Flip(0))  { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }

No, I'm not serious.


Just because I like to question code. I propose that you can also make use of the ternary by doing something like this:

Example:

bool flipValue = false;
bool bShouldFlip = true;
flipValue = bShouldFlip ? !flipValue : flipValue;

This seems to be a free-for-all ... Heh. Here's another varation, which I guess is more in the category "clever" than something I'd recommend for production code:

flipVal ^= (wParam == VK_F11);
otherVal ^= (wParam == VK_F12);

I guess it's advantages are:

  • Very terse
  • Does not require branching

And a just as obvious disadvantage is

  • Very terse

This is close to @korona's solution using ?: but taken one (small) step further.


For integers with values of 0 and 1 you can try:

value = abs(value - 1);

MWE in C:

#include <stdio.h>
#include <stdlib.h>
int main()
{
        printf("Hello, World!\n");
        int value = 0;
        int i;
        for (i=0; i<10; i++)
        {
                value = abs(value -1);
                printf("%d\n", value);
        }
        return 0;
}

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;

The codegolf'ish solution would be more like:

flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
otherVal = (wParam == VK_F12) ? !otherVal : otherVal;

Easiest solution that I found:

x ^= true;

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>

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


flipVal ^= 1;

same goes for

otherVal

Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to c

conflicting types for 'outchar' Can't compile C program on a Mac after upgrade to Mojave Program to find largest and second largest number in array Prime numbers between 1 to 100 in C Programming Language In c, in bool, true == 1 and false == 0? How I can print to stderr in C? Visual Studio Code includePath "error: assignment to expression with array type error" when I assign a struct field (C) Compiling an application for use in highly radioactive environments How can you print multiple variables inside a string using printf?

Examples related to boolean

Convert string to boolean in C# In c, in bool, true == 1 and false == 0? Syntax for an If statement using a boolean Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all() Ruby: How to convert a string to boolean Casting int to bool in C/C++ Radio Buttons ng-checked with ng-model How to compare Boolean? Convert True/False value read from file to boolean Logical operators for boolean indexing in Pandas

Examples related to boolean-logic

pandas: multiple conditions while indexing data frame - unexpected behavior How can I obtain the element-wise logical NOT of a pandas Series? How to test multiple variables against a value? Any good boolean expression simplifiers out there? if (boolean == false) vs. if (!boolean) How do I test if a variable does not equal either of two values? Differences in boolean operators: & vs && and | vs || Check if at least two out of three booleans are true How to convert "0" and "1" to false and true Does Python support short-circuiting?