Main Content

MISRA C++:2008 Rule 5-0-1

The value of an expression shall be the same under any order of evaluation that the standard permits

Description

Rule Definition

The value of an expression shall be the same under any order of evaluation that the standard permits.

Rationale

If an expression results in different values depending on the order of evaluation, its value becomes implementation-defined.

Polyspace Implementation

Polyspace® raises a violation if an expression satisfies any of these conditions:

  • The same variable is modified more than once in the expression or it is both read and written.

  • The expression allows more than one order of evaluation.

  • The expression contains a single volatile object that occurs multiple times.

  • The expression contains more than one volatile object.

Because volatile objects can change their value at anytime, an expression containing multiple volatile variables or multiple instances of the same volatile variable might have different results depending on the order of evaluation.

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

int a[10], b[10];
#define COPY_ELEMENT(index) (a[(index)]=b[(index)]) 
void main () {
    int i=0, k=0;

    COPY_ELEMENT (k);         // Compliant 
    COPY_ELEMENT (i++);    // // Non-compliant  
}

In this example, the rule is violated by the statement COPY_ELEMENT(i++) because i++ occurs twice and the order of evaluation of the two expressions is unspecified.

void f (unsigned int param1, unsigned int param2) {}

void main () {
    unsigned int i=0;
    f ( i++, i );                 // Noncompliant 
}

In this example, the rule is violated because it is unspecified whether the operation i++ occurs before or after the second argument is passed to f. The call f(i++,i) can translate to either f(0,0) or f(0,1).

volatile int a, b;
int mathOp(int x, int y);

int foo(void){
	int temp = mathOp(5,a) + mathOp(6,b);//Noncompliant
	return temp * mathOp(a,a);//Noncompliant
}

In this example, this rule is violated twice.

  • The declaration of temp uses two volatile objects in the expression. Because the value of volatile objects might change at any time, the expression might evaluate to different values depending on the order of evaluation. Polyspace flags the second volatile object in the expression.

  • The return statement uses the same volatile object twice. Because the expression might have different results depending on the order of evaluation, Polyspace raises this defect.

Check Information

Group: Expressions
Category: Required

Version History

Introduced in R2013b

expand all