Can I use bitwise operators instead of logical ones?

前端 未结 5 1694
青春惊慌失措
青春惊慌失措 2021-01-18 04:52

Bitwise operators work on bits, logical operators evaluate boolean expressions. As long as expressions return bool, why don\'t we use bitwise operators instead

5条回答
  •  情歌与酒
    2021-01-18 05:22

    Even if you achieve the same result with the bit-wise operator, it's better to use logical operator here due to performance reason.

    In expression (age < 0) || (age > 100) second condition (age > 100) will be calculated only if (age < 0) is false. For such expression compiler produce code like this:

    cmpl   $0x0,-0x4(%rbp)                 
    js     1004010f9   // <-- Skip right expr evaluation if left true
    cmpl   $0x64,-0x4(%rbp)               
    jle    100401100 
    

    || doesn't produce any extra branching to be able to skip second expression evaluation.

提交回复
热议问题