I've the following code.if i give control_word as 6 why if condition evaluates to true and enters inside if block?what exactly is happening here?
#define MACRO1 0x01
#define MACRO2 0x02
#define MACRO4 0x04
#define MACRO3 MACRO1 | MACRO2
#define MACRO7 MACRO4 | MACRO3
int main()
{
if(control_word == MACRO3 || control_word == MACRO7)
{
/*DO SOME OPERATION*/
}
else
{
/*DO SOMETHING ELSE */
}
}
The precedence of the | and == operators is not that you think it is. Moral: always parenthesize your macros!
#define MACRO3 (MACRO1 | MACRO2)
#define MACRO7 (MACRO4 | MACRO3)
So what happens is the expression expands to
control_word == 0x01 | 0x02 || control_word == 0x01 | 0x02 | 0x04
which in turn forms
(control_word == 1) | 2 || (control_word == 7) | 6)
that is
0 | 2 || 0 | 6
so all in all it's
2 || 6
which is interpreted by C as "true or true", and that yields true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With