A very commonly observed precedence error during usage of expressions is inadequate parenthesizing. Here we take examples of Equality/Inequality expressions:
if(var1 & var2 == 0)
The above is incorrect because == has a higher precedence than &, therefore in the above expression var2==0 will be computed first, which is a bool. Then that bool will be bit_AND'ed with var1. And this was not our intention.
The correct way is:
if((var1 & var2) == 0)
In practice, the test for equality/inequality must be the last logical operation, but it can happen otherwise, if there are operators of lower precedence than == or != in the expression.
If we recall our three liner:
S—U—Ari
Re—Bit—Lo—C
Assignment—Comma
The “e” in Re stands for equality/inequality, and when they are there in an expression with operators of lower precedence then the == or != will get executed earlier. To change the order of evaluation we need to appropriately parenthesize these operators. These operators(with precedence lower than == and != ) are Bit—Lo—C—Assignment—Comma. In practice we will find bit and assignment operator mixed with == and != operators.
So when we see this mixture, i.e.,== or !=, &, | , ^, = in a statement, parenthesis are to be taken care.
The following are some examples where precedence errors are very common.
a) Test if FLAG_A is clear in message incorrect
if(message & FLAG_A == 0)
correct
if((message & FLAG_A) == 0)
b) Test if FLAG_ A is set in message incorrect
if(message & FLAG_A != 0)
correct
if((message & FLAG_A) != 0)
c) Test if all flags are clear incorrect
if ( message & (FLAG_A | FLAG_B | FLAG_C) == 0)
correct
if (( message & (FLAG_A | FLAG_B | FLAG_C)) ==0)
d) Incorrect
if ( c = getchar() != EOF)
correct
if (( c = getchar()) != EOF)
In all the above cases, parenthesizing is to be done for operands with precedence lower than == or != so that they are executed earlier.
In short, when and expression has equality/inequality operator as the final operand and we see that there are operators in the expression whose precedence levels and are still lower than equality / inequality, then we should get the parenthesis correct. The operators with lower precedence than “Re” are Bit—Lo—C—Assignment—Comma
No comments:
Post a Comment