Main Content

AUTOSAR C++14 Rule M5-14-1

The right hand operand of a logical &&, || operators shall not contain side effects

Description

Rule Definition

The right hand operand of a logical &&, || operators shall not contain side effects.

Rationale

When evaluated, an expression that has side effects modifies at least one of the variables in the expression. For instance, n++ is an expression with side effect.

The right operand of a:

  • Logical && operator is evaluated only if the left-hand operand evaluates to true.

  • Logical || operator is evaluated only if the left-hand operand evaluates to false.

In other cases, the right operands are not evaluated. Side effects of the expression do not take place. If your program relies on such side effects, you might see unexpected results.

Polyspace Implementation

The checker flags logical && or || operators whose right operands are expressions that have side effects. Polyspace® assumes:

  • Expressions that modifies at least one of its variables have side effects.

  • Explicit constructors or conversion functions that are declared but not defined have no side effects. Defined conversion functions have side effects.

  • Volatile accesses and function calls have no side effects.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class real32_T {
public:
	real32_T() = default;

	/* Casting operations */
	explicit real32_T(float a) {
		// ...
	}
	/* Relational operators */
	bool operator==(real32_T a) const;
	bool operator>(real32_T a) const;
};

void bar() {
	real32_T d;


	
	if ((d == static_cast<real32_T>(0.0F))
	|| (static_cast<real32_T>(0.0F) > d)) {//Noncompliant
		/**/
	}
}



void foo(int i, int j){
	if(i==0 && ++j==i){ //Noncompliant
		--i;
	}
}

In the function foo, the right operand of the && operator contains an increment operation, which has a side effect. Polyspace flags the operator. In the function bar, the right operand of the || operator contains a conversion function that is implemented in the class. Polyspace considers such constructor to have side effects. Because the right operator has side effects, the operator is flagged.

Check Information

Group: Expressions
Category: Required, Automated

Version History

Introduced in R2019a