【问题标题】:How to translate if .. else statement with goto?如何用 goto 翻译 if .. else 语句?
【发布时间】:2019-04-08 00:53:40
【问题描述】:

我必须将嵌套 if..else 条件转换为 C 代码中的 goto 标签。 我知道我必须从外部 if-s 开始,但是如何用 goto 翻译内部 if-s?

Example: if(condition)
          {
            if(condition)
            {
             if(condition)
              {
                statements;
              }
              if(condition) return;
              statements;
            }  
          }
        else statements;

【问题讨论】:

  • 创建与原始程序中每个块相对应的代码序列。给它们贴上标签。插入goto 语句以连接它们。只需要初步推理。
  • if (X) { statements A } else { statements B } 可以改写为if (X) goto A; { statements B } goto E; A: { statements A } E: ; 通过替换(就像在高中代数中一样),您可以从中得到答案。一次只替换一个 if-then-else。
  • 为什么?它会让事情变得一团糟。
  • 使用 go to 是不合逻辑的。但是,您需要以某种方式比较或检查这些值。您可以使用“?”,然后将行标记为“A:”,然后使用 goto A
  • 如果你想在非常低的级别创建 if else 链,你必须使用程序集

标签: c if-statement goto


【解决方案1】:

实际上,您不需要翻译Ìf statement 或任何属于C 的语句。 你可以直接这样使用,它会自动翻译成Assembly

int main(void)
{
    unsigned char SerData = 0x44;
    unsigned char TempSerData;
    unsigned char x;
    TempSerData = SerData;
    DDRC |= (1<<SerPin); //configure PORT C pin3 as output
    for (x=0;x<8;x++)
    {
       if (TempSerData & 0x01) // check least significant bit
             PORTC |= (1<<serPin); // set PORT C pin 3 to 1
       else
          PORTC &= ~(1<<serPin); // set PORT C pin 3 to 0
       TempSerData = TempSerData >> 1; // shift to check the next bit
    }
    return 0;
}

但是,如果你想翻译if,你可以使用这样的东西,但正如我所说,你不需要转换它,或者你不需要C来完成这项工作。

int x = 0, y = 1;
(x >= y) ? goto A: goto B
A: // code goes here 
    goto end
B: // code goes here  
    goto end
end: return 0;

在汇编中,你可以很容易地做到这一点。例如在Àtmega128:

ldi r16, 0x00 ; load register 16 with 0
ldi r17, 0x01 ; load register 17 with 1

sub r17, r16  ; take the difference
brcs if_label
else_label:             ; do some operation on that line or on the other lines
          rjmp end
if_label:               ; do some operation on that line or on the other lines     
end: rjmp end           ; program finishes here

【讨论】:

  • 您不能将goto 用作条件运算符的一部分。
  • 一个在线编译器让我这样做,所以我想我可以使用它@pmg
  • 你能分享一下在线编译器允许在条件运算符中使用goto 语句吗?谢谢
猜你喜欢
  • 2022-11-30
  • 1970-01-01
  • 2021-12-25
  • 2014-05-12
  • 1970-01-01
  • 2019-04-09
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
相关资源
最近更新 更多