incompatability of the ternary operator

53 views Asked by At
#define BIT2 (1 << 2) 
#define BIT0 (1 << 0) 

unsigned int a = 0, temp = 0;

#define setBit2_a (a |= BIT2) 
#define clearBit2_a (a &= ~BIT2)

#define setBit0_a (a |= BIT0) 
#define clearBit0_a (a &= ~BIT0)
void main()
{
    a=4; //use a scanf here for convinient
    temp = a;

    a & BIT0 != 0 ? setBit2_a : clearBit2_a;
    temp & BIT2 != 0 ? setBit0_a : clearBit0_a;        

    printf("the number entered is a = %u\n\r", a);
}

this should set the bit 0 in the variable a , but its not doing so in ubuntu gcc complier can anybody please explain this

2

There are 2 answers

0
augustine nishil On BEST ANSWER

all that is to be noted here is: the operator precedence for == is stronger than for & so the evaluated results which is always false and we need to use the braces here in accordance with the precedence and the BODMAS rule.

0
BeyelerStudios On

Note that you probably expect a different result from your expression a & (1 << 2) != 0: the operator precedence for == is stronger than for & so the evalution results in a & ((1 << 2) != 0) which is always false for your ternary operator since 4 & 1 == 0

You want: (a & (1 << 2)) != 0 ? ...; or a & 4 ? ...;