Monday, March 22, 2010

Avoid nested assignment statements





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


Description

"Apart from a few operators (notably the function call operator (), &&, , ?: and , (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This means that no reliance can be placed on the order of evaluation of sub-expressions, and in particular no reliance can be placed on the order in which side effects occur. Those points in the evaluation of an expression at which all previous side effects can be guaranteed to have taken place are called “sequence points”. Sequence points and side effects are described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].

Note that the order of evaluation problem is not solved by the use of parentheses, as this is not a precedence issue."

"Assignments nested within expressions cause additional side effects. The best way to avoid any chance of this leading to a dependence on order of evaluation is to not embed assignments within expressions.

For example, the following is not recommended:

x = y = y = z / 3;

x = y = y++;"

Benefits:

Rule prevents evaluation of expression dependent on compiler version.

Example:

void foo( int x, int y, int z ) {

   x = y = z / 3;  // Violation
}

Repair:

void foo( int x, int y, int z ) {
   y = z / 3;  // OK
   x = y;      // OK
}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 12

Author
ParaSoft

No comments:

Post a Comment

Labels