c - 如何用 goto 翻译 if .. else 语句?

标签 c if-statement goto

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

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

最佳答案

实际上,您不需要翻译Ìf语句或任何属于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

关于c - 如何用 goto 翻译 if .. else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564992/

相关文章:

c - 得到错误而不是不兼容的指针类型警告

c - c中的双分号是什么意思?

c - 字符串中的 `% a` 读取为内存中的一个点

C - if-else 语句卡住并崩溃

if-statement - 代码执行条件错误?

c - 转到内部开关盒工作异常

C 从 FILE* 打印文件路径

Python Pandas Dataframe 条件 If、Elif、Else

goto - 我如何重组此控制流以避免使用 goto?

c++ - 通过函数指针计算的 goto/jump 与 fastcall 哪个成本更高?