MISRA.EXPR.PARENS.REDUNDANTLimited dependence required for operator precedence rules in expressions. Redundant use of parenthesis in an expression. MISRA-C Rule 12.1 (advisory): Limited dependence should be placed on C's operator precedence rules in expressions.In addition to the use of parentheses to override default operator precedence, parentheses should also be used to emphasize it. It is easy to make a mistake with the rather complicated precedence rules of C, and this approach helps to avoid such errors, and helps to make the code easier to read. However, do not add too many parentheses so as to clutter the code and make it unreadable. The following guidelines are suggested in deciding when parentheses are required:
x = a + b; /* acceptable */ x = (a + b); /* () not required */
x = a * -1; /* acceptable */ x = a * (-1); /* () not required */
x = a + b + c; /* acceptable, but care needed */ x = f (a + b, c); /* no () required for a + b */ x = (a == b) ? a : (a - b); if (a && b && c) /* acceptable */ x = (a + b) - (c + d); x = (a * 3) + c + d; x = (uint16_t) a + b; /* no need for ((uint16_t) a) */
uint16_t a = 10U; uint16_t b = 65535U; uint32_t c = 0U; uint32_t d; d = (a + b) + c; /* d is 9; a + b wraps modulo 65536 */ d = a + (b + c); /* d is 65545 */ /* this example also deviates from several other rules */ Note that Rule 12.5 is a special case of this rule applicable solely to the logical operators, '&&' and '||'. MISRA-C++ Rule 5-0-2 (advisory): Limited dependence should be placed on C++ operator precedence rules in expressions.RationaleIn addition to the use of parentheses to override default operator precedence, parentheses should also be used to emphasize it. It is easy to make a mistake with the rather complicated precedence rules of C++, and this approach helps to avoid such errors, and helps to make the code easier to read. However, too many parentheses can clutter the code and make it unreadable. ExampleThe following guidelines are suggested for deciding when parentheses are required:
x = a + b; // acceptable x = (a + b); // () not required
x = a * -1; // acceptable x = a * (-1); // () not required Otherwise, the operands of binary and ternary operators shall be cast-expressions (see Section 5.4(2) of ISO/IEC 14882:2003 [1]) unless all the operators in the expression are the same. x = a + b + c; // acceptable, but care needed x = f ( a + b, c ); // no () required for a + b x = ( a == b ) ? a : ( a — b ); if ( a && b && c ) // acceptable x = ( a + b ) — ( c + d ); x = ( a * 3 ) + c + d; x = static_cast< uint16_t > ( a ) + b; // no need for cast
uint16_t a = 10U; uint16_t b = 65535U; uint32_t c = 0U; uint32_t d; d = (a + b) + c; // d is 9; a + b wraps modulo 65536 d = a + (b + c); // d is 65545 // this example also deviates from several other rules Note that Rule 5—2—1 is a special case of this rule applicable solely to the logical operators, '&&' and '||'. |