incompatability of the ternary operator

时间:2015-06-25 10:03:19

标签: gcc ternary-operator operator-precedence

#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 个答案:

答案 0 :(得分:1)

请注意,您可能希望表达式a & (1 << 2) != 0产生不同的结果:==的{​​{3}}强于&,因此评估结果为{{1}自a & ((1 << 2) != 0)

以来,对于您的三元运算符始终为false

您想:4 & 1 == 0(a & (1 << 2)) != 0 ? ...;

答案 1 :(得分:-1)

这里要注意的是: ==的运算符优先级强于&amp;所以评估结果总是错误的,我们需要根据优先级和BODMAS规则使用括号。