2016-11-21 221 views
-4
for (int i = 0; i < 6; i++) { 
    led_r1 = ~led_r1; 
    led_r2 = ~led_r2; 
    led_l1 = 0; 
    led_l2 = 0; 
    DelayMs(60); 
    if (check == 1) { 
     check = 0; 
     right_check = 0; 
     left_check = 0; 
     goto new_pattern; 
    } 
    if (off == 2) { 
     off = 1; 
     right_check = 0; 
     left_check = 0; 
     goto reset; 
    } 
} 

这是我的代码来闪烁两个LED在我的项目... 它工作正常,但我的程序是正确的......? 这种使用goto语句的方式是正确的..? 它会崩溃程序enter code here上午..? enter code herec语言中断循环

是他们的任何其他方式终止程序并跳转到程序的其他部分

+0

您是否知道C处已经有一个'破'命令?你为什么不使用它? –

+1

Goto声明被认为是有害的。这是在1968年的突发新闻。 – Lundin

+0

在我的程序中看到如果(关== 2)如果它发生我必须另一个位置..?我怎样才能做到没有goto语句..我是新来的c语言。请给我建议解决方案 – steve

回答

0

这是相当困难根据您所提供的代码来回答你的问题,因为你没有给会怎么样任何解释在new_pattern:reset:标签上,或者您如何期望变量的值在没有可能导致此情况发生的指令的循环内发生变化。

但是,正如Lundin在评论中指出的那样,您应该尝试avoid the use of goto statements whenever possible。它们往往会导致代码不可读,不可维护。

相反,您应该尝试遵循structured programming的原则。特别是,你应该考虑使用函数来更合理地组织你的代码。 (选择适当的描述函数的名称也将让你的代码更容易理解。)

你的代码的结构重新工作可能是这个样子:

#define NO_CHANGE  0 
#define UPDATE_PATTERN 1 
#define RESET_LEDS  2 

int main() { 
    /* ... */ 
    switch(flash_leds()) { 
     case UPDATE_PATTERN: 
      new_pattern(); 
      break; 
     case RESET_LEDS: 
      reset(); 
      break; 
     default: 
      /* Done flashing; no action required */ 
    } 
    /* ... */ 
} 

int flash_leds() { 
    for (int i = 0; i < 6; i++) { 
     /* ... */ 
     if (check == 1) return UPDATE_PATTERN; 
     if (off == 2) return RESET_LEDS; 
    } 
    return NO_CHANGE; 
} 

void new_pattern() { 
    /* update the pattern displayed by the LEDs */ 
} 

void reset() { 
    /* reset the LEDs */ 
}