今天写一个程序,因为没有加括号,导致实际的运算优先级和认为的不一样,花了不少冤枉时间。
问题是这样的,
A & B == B
我想要的evaluation 顺序是 (A & B ) == B, 而且认为 &优先级高于 ==.
实际上并非如此。所以,实际的顺序是 A & (B == B).
这个优先级可以从man 里面查到。方法是 man operator
OPERATOR(7) Linux Programmer's Manual OPERATOR(7)
NAME
operator - C operator precedence and order of evaluation
DESCRIPTION
This manual page lists C operators and their precedence in evaluation.
Operator Associativity
() [] -> . left to right
! ~ ++ -- + - (type) * & sizeof right to left
* / % left to right
+ - left to right
<< >> left to right
< <= > >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
= += -= *= /= %= <<= >>= &= ^= |= right to left
, left to right
如果不知道 有 operator也没关系,可以通过关键字查询:
man -k precedence
operator (7) - C operator precedence and order of evaluation