Easiest way to flip a boolean value?

前端 未结 13 1483
后悔当初
后悔当初 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: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;
    

提交回复
热议问题