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

时间:2019-04-08 00:53:40

标签: c if-statement goto

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

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

1 个答案:

答案 0 :(得分:-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来完成这项工作。 / p>

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