TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
ASML C Coding Standard
Search

Rule:  5.1.2.3.bChecked automatically with code checker

Synopsis:Expressions which mix operators from the set ">", ">=", "<", "<=", "==", "!=" with the binary operators from the set "<<", ">>", "^", "&", "|", "&&", "||" and which use two or more distinct operators from the latter set shall be fully parenthesized and shall not depend on the C precedence rules.
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 < j < k) /* WRONG */
{
   /* any statement */
}

Example 4

if ((i > j) && (j > k)) /* RIGHT */
{
   /* any statement */
}

Example 5

if (i != 10) /* RIGHT: comparison of 1 value */
...

Example 6

if (i - k == 10 && j - k == 10) /* WRONG: precedence not clear  */
...

Example 7

if (((i - k) == 10) && ((j - k) == 10)) /* RIGHT */
...

Example 8

if (i <= 10) /* RIGHT: comparison of 1 value */
...

Example 9

if (i - k > 10 && j - k < 10) /* WRONG: precedence not clear */
...

Example 10

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!