Tuesday, March 23, 2010

Function call order




The value of an expression shall be the same under any order of evaluation that the standard permits (misra2004_12_2_4_FunctionsCallOrder.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." "Functions may have additional effects when they are called (e.g. modifying some global data). Dependence on order of evaluation could be avoided by invoking the function prior to the expression that uses it, making use of a temporary variable for the value.

For example

x = f(a) + g(a);

could be written as

x = f(a);

x += g(a);

As an example of what can go wrong, consider an expression to get two values off a stack, subtract the second from the first, and push the result back on the stack:

push( pop() - pop() );

This will give different results depending on which of the pop() function calls is evaluated first (because pop() has side effects)."

Benefits:

Rule prevents evaluation of expression dependent on compiler version.

Example:

int foo( int x ) {

   if (x < 0)
   {
       return 0;
   }

   return foo( x - 1 ) - foo( x - 2 );  // Violation

}

Repair:

int foo( int x ) {

   int y;

   if (x < 0)
   {
       return 0;
   }
   y = foo( x - 1 );

   return y - foo( x - 2 );   // 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