AutosarC++18_03-M5.0.2

Limited dependence should be placed on C++ operator precedence rules in expressions

Required inputs: IR

Rationale

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, too many parentheses can clutter the code and make it unreadable.

Example

The following guidelines are suggested for deciding when parentheses are required:

  • Parentheses are not required for the right-hand operand of an assignment operator unless the right-hand side itself contains an assignment expression:
    x = a + b;      // acceptable 
    x = (a + b); // () not required
  • Parentheses are not required for the operand of a unary operator:
    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) 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
  • Even if all operators are the same, parentheses may be used to control the order of operation. Some operators (e.g. addition and multiplication) that are associative in algebra are not necessarily associative in C++. Similarly, integer operations involving mixed types (prohibited by several rules) may produce different results because of the integral promotions. The following example written for a 16-bit implementation demonstrates that addition is not associative and that it is important to be clear about the structure of an expression:
    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 ||.

Note

For legal reasons, this rule’s description is not part of the public documentation.