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 expression
expands to
which eventually expands to
looking at the precedence table, you see that operator
==has higher precendence than|, which is higher than||, so the evaluation is:which evaluates to
which is (
6==1isfalse, which is treated as 0 in the arithmetic expression — same for6==4)which is
which is
as 2 and 3 are treated as
true(non-zero), so you enter theifblock, not theelseTo preserve the (presumed) intent (and get the result you exprected) you need to protect the expansion of the macros by wrapping their definition in parentheses — note that this is always a good idea to avoid the dissonance between what you think and what is actually happening.