Logical Operators in C

前端 未结 8 2006
说谎
说谎 2020-11-27 08:25

I am having trouble trying to understand how logical operators work in C. I already understand how the bit-level operators work, and I also know that logical operators treat

相关标签:
8条回答
  • 2020-11-27 09:14

    C and C++ has three logical operators: logical not(!), logical and(&&) and logical or(||). For logical operators, 0 is false and anything that is not zero is true. This truth table illustrates how each logical operator works(will be using 1 for true):

    p     q     p && q    p || q
    =     =     ======    ======
    1     1       1         1
    1     0       0         1
    0     1       0         1
    0     0       0         0
    

    The truth table for ! is as follows:

    p    !p
    =    ===
    1     0
    0     1
    

    For your specific case:

    0x65 && 0x55
    

    Since both operands 0x65 and 0x55 evaluate to true the whole expression evaluates to true and thus expands to 1, which applies to c99 but other answers in the linked thread explain how it applies before c99 as well.

    0 讨论(0)
  • 2020-11-27 09:25

    The && is a logical AND (as opposed to &, which is a bitwise AND). It cares only that its operands as zero/non-zero values. Zeros are considered false, while non-zeros are treated as true.

    In your case, both operands are non-zero, hence they are treated as true, resulting in a result that is true as well. C represents true as 1, explaining the overall result of your operation.

    If you change the operation to &, you would get a bitwise operation. 0x65 & 0x55 will give you a result of 0x45.

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