When Operator Precedence Hits You Hard

Take the following piece of code for example:

void main(void) {

 int a = 24;
 int b = 8;

 if (a & b != 0) 

Considering that 24 & 8 equals 8, the first glance assumption is that this code will print A. However, due to operator precedence, the if condition is equivalent with:

a & (b != 0)

As b is not 0, and a is not odd, the code will print B. So to ensure that & is evaluated first, parentheses should be used around a & b, like this:

if ( (a & b) != 0)

The general rule of thumb is that, if you don’t want to keep track of  precedence rules, you should always use parentheses on the expression involved in relational operations.

Otherwise, remember that arithmetic operators (i.e. multiplication, division, modulus, addition and subtraction) and bitwise shift operators have higher precedence and do not require parentheses. On the other hand, logical operators (bitwise or logical) have lower precedence and need parentheses in relational expressions (unless of course, you do it on purpose).

[1] Any C operator precedence table ( I used this )

Subscribe to my mailing list
100% Privacy. I don't spam.

Leave a Reply

Your email address will not be published. Required fields are marked *