Easiest way to flip a boolean value?

前端 未结 13 1443
后悔当初
后悔当初 2020-12-04 08:31

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:

swi         


        
相关标签:
13条回答
  • 2020-12-04 09:18

    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)

    0 讨论(0)
  • 2020-12-04 09:21

    Easiest solution that I found:

    x ^= true;
    
    0 讨论(0)
  • 2020-12-04 09:23

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

    0 讨论(0)
  • 2020-12-04 09:26

    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;
    }
    
    0 讨论(0)
  • 2020-12-04 09:30

    The codegolf'ish solution would be more like:

    flipVal = (wParam == VK_F11) ? !flipVal : flipVal;
    otherVal = (wParam == VK_F12) ? !otherVal : otherVal;
    
    0 讨论(0)
  • 2020-12-04 09:35

    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;
    
    0 讨论(0)
提交回复
热议问题