为什么我的C程序跳过这个if语句?

时间:2016-11-17 17:27:53

标签: c microcontroller code-composer

我有这个C程序,我在代码作曲家工作室写作。

#include <msp430.h> 

/*
 * main.c
 */
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD;    // Stop watchdog timer

    int R5_SW=0, R6_LED=0, temp=0;

    P1OUT = 0b00000000;     // mov.b    #00000000b,&P1OUT
    P1DIR = 0b11111111;     // mov.b    #11111111b,&P1DIR
    P2DIR = 0b00000000;     // mov.b    #00000000b,&P2DIR

    while (1)
    {
        // read all switches and save them in R5_SW
    R5_SW = P2IN;

    // check for read mode
        if (R5_SW & BIT0)
          {
            R6_LED = R5_SW & (BIT3 | BIT4 | BIT5); // copy the pattern from the switches and mask
            P1OUT = R6_LED;            // send the pattern out
          }

        // display rotation mode
        else
            {
            R6_LED = R5_SW & (BIT3|BIT4|BIT5);
            // check for direction
            if (R5_SW & BIT1) {// rotate left
                R6_LED << 1;
            } else {
                R6_LED >> 1;
            }   // rotate right

            // mask any excessive bits of the pattern and send it out
            R6_LED &= 0xFF;             // help clear all bits beyound the byte so when you rotate you do not see garbage coming in
                P1OUT = R6_LED;

                // check for speed
            if (R5_SW & BIT2)   {__delay_cycles( 40000); }  //fast
                else            {__delay_cycles(100000); }  //slow
         }
    }
}

如果在调试模式下发表声明

if (R5_SW & BIT1) {// rotate left
    R6_LED << 1;
} else {
    R6_LED >> 1;
}   // rotate right

它跳过它,它没有运行if或else块。此时,代码R5_SW中的22为二进制0010 0010,因此R5_SW & BIT1应评估为true。我在这里缺少什么?

2 个答案:

答案 0 :(得分:5)

如果您使用<<>>之类的操作而未指定它,则结果将被丢弃。试试这个:

if (R5_SW & BIT1) {// rotate left
           R6_LED = R6_LED << 1;
        } else {
            R6_LED = R6_LED >> 1;
        }   // rotate right

或者,为简洁起见:

if (R5_SW & BIT1) {// rotate left
            R6_LED <<= 1;
        } else {
            R6_LED >>= 1;
        }   // rotate right

答案 1 :(得分:3)

这段代码......

if (R5_SW & BIT1) {// rotate left
    R6_LED << 1;
} else {
    R6_LED >> 1;
}   // rotate right

计算表达式R6_LED >> 1或表达式R6_LED << 1,但它对结果没有任何作用,因此编译器选择将其抛弃整个IF语句。

a>>b这样的行本身不会修改a。它不像a++那样修改a