Synopsis: | If in doubt about operator precedence, parenthesize. |
Language: | C |
Severity Level: | 8 |
Category: | Conceptual Models |
Description: |
Justification Mixing relational and logical operators without explicitly adding parenthesis is a notorious source of error in C programs. However, care must be taken changing existing code which is not properly parenthesized. The precedence of operators in C is not intuitive. Extra parentheses aid the reader to establish the grouping of operands. Example 1 if (a == b && c == d && d != 0) /* WRONG */ { /* any statement */ } Example 2 if ((a == b) && (c == d) && (d != 0)) /* RIGHT */ { /* any statement */ } Example 3 if (i != 10) /* RIGHT: comparison of 1 value */ ... Example 4 if (i - k == 10 && j - k == 10) /* WRONG: precedence not clear */ ... Example 5 if (((i - k) == 10) && ((j - k) == 10)) /* RIGHT */ ... Example 6 if (i <= 10) /* RIGHT: comparison of 1 value */ ... Example 7 if (i - k > 10 && j - k < 10) /* WRONG: precedence not clear */ ... Example 8 if (((i - k) > 10) && ((j - k) < 10)) /* RIGHT */ ... Note Relational operators ("<=", "<", ">" and ">=") have a higher priority than the equality operators ("==" and "!="). Be careful with changing existing code which is not properly parenthesized! |