Search code examples
cmsp430

Why does this if statement not run?


I have this C code, and neither the if or else block is running when I go through it with the debugger

Here is the code:

if(P2IN & BIT4 == BIT4 ){
    car_lock ^= BIT0;
    is_pressed = 1;
}else{
    is_pressed = 0;
}

At this point in the code, P2IN = 00010000

It seems like neither the if or else block is running, what am I missing?


Solution

  • The problem is in your if statement. The == operator takes higher precedence than the &, so what's really being evaluated is:

    (P2IN & (BIT4 == BIT4))
    

    You need to change your code to:

    if ((P2IN & BIT4) == BIT4)
    

    There's a useful webpage about operator precedence here.