-
Strange side effects?
I'm using a compiler that is a lot more strict on the C language than normal (it's meant to help create less bugs in the code).
One thing I'm confused at is that it complains about the following line of code:
if ((timer == 0) && ((status & 0x100) == modval))
with:
Error: the right hand operand of an && or || operator should not contain side effects
So, can anyone see the side effect it's complaining about? As I certainly can't. Also, why is it specifc about the right hand side?
If I remove the "== modval" on the right hand side, I get the following additional error:
Error: this bitwise operation is in a boolean context
Which is understandable, as it doesn't evaluate to a proper boolean result, but rather assumes that true is anything apart from zero.
Still doesn't explain why it thinks "status & 0x100" gives a side effect tho'
EDIT: 'status' is a volatile. That explains it. Why only the right hand side though?
-
In C, the right hand side of an && expression is guaranteed to be only evaluated if the left hand side is true. The left hand side will always be evaluated.
-
What compiler are you using?
-
> Error: the right hand operand of an && or || operator should not contain side effects
As cwr states, the right hand side may NOT be evaluated, so any 'side' effects will not happen if the left hand side evaluates to false to start with.
> EDIT: 'status' is a volatile.
If this is mapped to some piece of hardware which detects whether it's been read or not (say), then knowing that it may not be read as often as your code suggests is probably something you need to know.
You can alter the code like so
temp = status; // force a read of the volatile
if ((timer == 0) && ((temp & 0x100) == modval)) // evaluate using a non-volatile
-
^XOR: The compiler is IAR.
Salem: Thanks, I did actually want the said behavior, but at least I know now /why/ the compiler was complaining. Since other people may want to edit the code once it's released, I think this is probably a good thing, as they may not be thinking about the code in the same way as me, and then create bugs with that misunderstanding.