Boolean Precedence

Boolean Precedence

The above examples use parentheses to spell out the order of operations. The boolean not ! has a high precedence -- in (!a && b) the ! is evaluated on the a, before the &&. We could add in parenthesis (!(a && b)) to force the && to evaluate before the !. The && operator is higher precedence than ||, so in (a || b && c), the && happens first. There are parallels between the boolean operators and arithmetic: ! is like unary -, && is like *, || is like +. The comparison operators (<, <=, ==, ...) all have higher precedence than && and ||, so without parentheses, comparisons always happen before the && and ||. This is very convenient, since we can use <= to get some booleans, and then && and || to combine the booleans. So our earlier example:
if (! ((style>=8) && (bribe>=5))) {
works fine without parentheses around the comparisons, since the comparisons have high precedence than && ||:
if (! (style>=8 && bribe>=5)) {
The not ! has a high precedence (as do all the unary operators), so we need parentheses to force the ! to evaluate after the >= and &&. Remember that all the unary operators, such as !, have a high precedence. To evaluate something before the !, we frequently need to put the something in parentheses like this: !(something). For example:
if (! i < 10 ) { ...	// NO does not work
The precedence of the ! is too high, it wants to execute before the <. To fix this, we add parentheses around the (i < 10) so it goes first:
if (!(i < 10 )) { ...	// Ok

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值