【问题标题】:Why is my C program skipping over this if statement?为什么我的 C 程序会跳过这个 if 语句?
【发布时间】:2016-11-17 17:27:53
【问题描述】:

我有这个 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 语句时

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

它跳过它,它不运行 if 或 else 块。此时代码中的R5_SW22,它是二进制的0010 0010,所以R5_SW &amp; BIT1 应该评估为真。我在这里错过了什么?

【问题讨论】:

  • 您肯定在运行 if 或 else 之一,只是您没有存储计算。我想你的意思是R6_LED &lt;&lt;= 1;R6_LED &gt;&gt;=1;
  • 22 十进制为000101100x2200100010

标签: c microcontroller code-composer


【解决方案1】:

如果您使用&lt;&lt;&gt;&gt; 之类的操作而不分配它,则结果将被丢弃。试试这个:

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

【讨论】:

    【解决方案2】:

    这段代码……

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

    计算表达式R6_LED &gt;&gt; 1 或表达式R6_LED &lt;&lt; 1,但它不对其结果做任何事情,因此编译器选择将其丢弃整个IF 语句。

    a&gt;&gt;b 这样的行本身不会修改a。它不像 a++ 这样会修改 a

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-04
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多