What is the point of the logical operators in C?

后端 未结 5 1992
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 07:49

I was just wondering if there is an XOR logical operator in C (something like && for AND but for XOR). I know I can split an XOR into ANDs, NOTs and ORs but a simple

相关标签:
5条回答
  • 2020-12-18 08:10

    You don't need logical XOR, I have forgotten the SO question, but it's similar to what you're thinking, basically we don't need XOR, it's equivalent to != anyway

    FALSE XOR FALSE == FALSE
    FALSE XOR TRUE == TRUE
    TRUE XOR FALSE == TRUE
    TRUE XOR TRUE == FALSE
    
    
    FALSE != FALSE == FALSE
    FALSE != TRUE == TRUE
    TRUE != FALSE == TRUE
    TRUE != TRUE == FALSE
    

    I'll search my favorites, and paste here the link later...

    0 讨论(0)
  • 2020-12-18 08:11

    In C arguments of logical operators are treated as Boolean values - anything zero is treated as "false", and anything else (yes, negative values too) are "true". Bitwise ops work on individual bits, and as Neil already noted, are not subject to short-circuit evaluation as logical ops are.

    In your example the results are totally valid and expected since bit-wise xor between two ones is zero.

    0 讨论(0)
  • 2020-12-18 08:11

    If you want a logical xor operator in C, then you can use this:

    #define xor != 0 ^ !!
    

    It works by converting both sides of the expression to booleans and xoring them. You can use it as if you were using && or ||, like this:

    if (a xor b)
    

    AFAICT, there aren't any problems with it.

    0 讨论(0)
  • 2020-12-18 08:12

    Bitwise XOR does not work as would a logical XOR when its operands are integer values:

    2^4 ? "Valid" : "Invalid"
    

    gives "Valid" but should give "Invalid"

    0 讨论(0)
  • 2020-12-18 08:19

    The bitwise operators do not work "just the same" as the && and || operator. For a start, && and || perform short-circuited evaluation, whereas the the bitwise operators do not. In other words, you can't do something like this with the bitwise operators:

    int * p = 0;
    (p != 0) && (*p = 1);
    

    because if you said:

    (p != 0) & (*p = 1);
    

    both subexpressions would be evaluated, and you would dereference the null pointer.

    0 讨论(0)
提交回复
热议问题