Consider the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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:

1 |
if(x | f != 10) |

We maybe want it to be parsed as

1 |
if ( ( x | f ) != 10 ) |

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

1 |
if ( x | (f != 10)) |

this produced true (printing “yes”)

The second is:

1 2 |
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

1 |
r2 = x << (3+1) |

### Conclusion:

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