Parentheses should always be used as they reduce complexity. Explain it with the help of a single example.
Parentheses should always be used as they reduce complexity and clarify things by specifying grouping. It is especially important to use parentheses when different unrelated operators are used in the same expression as the precedence rules are often assumed by the programmers, resulting in logical errors that are very difficult to spot. As an example consider the following statement:
if (x & MASK == BITS)
This causes problems because == operator has higher precedence than & operator. Hence, MASK and BITS are first compared for equality and then the result, which is 0 or 1, is added with x. This kind of error will be extremely hard to catch. If, however, parentheses are used, there will be no ambiguity as shown below.
if ((x & MASK) == BITS)
if (x & MASK == BITS)
This causes problems because == operator has higher precedence than & operator. Hence, MASK and BITS are first compared for equality and then the result, which is 0 or 1, is added with x. This kind of error will be extremely hard to catch. If, however, parentheses are used, there will be no ambiguity as shown below.
if ((x & MASK) == BITS)
Parentheses should always be used as they reduce complexity
Reviewed by MCH
on
July 17, 2012
Rating:
No comments: