Operator Precedence Pitfalls

Consider the following code:

int main(void)
{
 int f=0x2; // 0010
 int x=0x8; // 1000
 int r1,r2;
 if(x | f != 10)
	printf("yes\n");
 else
	printf("no\n");

 r1 = x * 8 + 1;
 r2 = x << 3 + 1;

 if(r1==r2)
	printf("yes\n");
 else
	printf("no\n");


 return 0;
} 

It has 2 problems – both with assumptions on operator precedence:

the first one is the statement:

 if(x | f != 10)

We maybe want it to be parsed as

if ( ( x | f ) != 10 )

but the priority of != is above | so we get it parsed as

if ( x | (f != 10))

this produced true (printing “yes”)

The second is:

r1 = x * 8 + 1;
r2 = x << 3 + 1;

we all know from first grade the multiply and divide precede plus and minus.

Also any developer knows the multiply by 8 is the same as 3 bits shifting

But … the precedence of bit shifting is bellow plus so it parses the statement as

r2 = x << (3+1)

 

Conclusion:

Always use parentheses , don’t trust operator precedence (even if you liked your first grade teacher)