Example 2: Implicit Order of Evaluation
Code that relies on implicit order of evaluation can cause bugs that are difficult to find. PREfast for Drivers detects instances in which such code might produce results that are different from what the programmer intended.
When PREfast for Drivers detects an implicit order of evaluation, if reports Warning 6281, as shown in the following example.
___________________________________________________________________________
42 int unclearIntent(int a, int b, int c)
43 {
PREfast analysis path begins
44 if (a & b == c) return 1;
abc.cpp(44) : warning 6281: Incorrect order of operations: relational operators have higher precedence than bitwise operators.problem occurs in function 'unclearIntent'
45 return 0;
46 }
___________________________________________________________________________
According to the rules of operator precedence in C, the expression (a & b == c) is interpreted as (a & (b == c)) because the equality operator (==) has higher precedence than the bitwise AND operator (&). Therefore, this function compares b with c and then masks the result with a, which tests whether a is even or odd.
If this is the intended result, then the function is correct as it is written, but parentheses would help to make the programmer's intention clear (as would a comment in the code).
If the programmer intended to mask a with b and then compare the result with c, then the function is incorrect. Parentheses are required to force evaluation of the expression as ((a & b) == c).
Send comments about this topic to Microsoft
Build date: 5/3/2011