【问题标题】:About break statement in c programming and termination of a loop关于c编程中的break语句和循环的终止
【发布时间】:2021-05-20 13:20:25
【问题描述】:

我对这个程序中的break 语句有疑问。
从技术上讲,break 语句终止了它所在的循环,但在这个程序中,breakif 语句中。
所以,这里break 应该只终止if 语句,对吗?但它也终止了do-while 语句。
对不起,如果我问错了什么。我是编程新手

#include <stdio.h>

int main()
{
    int count;
    char response;

    for (count = 1; count <= 100; count++)
    {
        printf("count = %d\n", count);
    
        printf("enter y to continue or any other key to quit");
    
        scanf(" %c", &response);
    
        if (response != 'y')
            break;
    }

    printf("thank you!\n");
    return 0;
}

【问题讨论】:

  • if 不能被“终止”。 break 将“终止”最内部的循环或switch ... case
  • break 终止了for 循环,而不是if 代码块。与whiledo ...while 以及switch 情况类似,这不是循环。
  • 您能想象在任何情况下,像您认为的那样有效的中断会很有用吗? ;)

标签: c loops if-statement switch-statement break


【解决方案1】:

根据 C 标准(6.8.6.3 的 break 语句)

2 break 语句终止执行最小的封闭 switch 或迭代语句。

这个 if 语句中的这个 break 语句

if (response !='y')
    break;

终止执行封闭的 for 语句。

你可以想象它的动作如下

for (count=1;count<=100;count++){
    //...    
    if (response !='y')
    goto L1;
}
L1:
printf("thankyou!");

如果 if 语句未包含在迭代或 switch 语句中,则不能在 if 语句中使用 break 语句。

break 语句是一个跳转语句,它将控制传递到最小的封闭 switch 或迭代语句之外。

【讨论】:

    【解决方案2】:

    你可以在两种状态下使用“break”语句。

    1. 在循环中
    2. 在开关盒中 如果你在循环中使用。当 break 语句起作用时,循环将结束。 如果在 switch-case 中使用。当 break 语句在其中一种情况下起作用时,其他情况下不起作用。 隐式地,循环结束了,如果块不会再次运行。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 2017-06-09
      • 1970-01-01
      • 2017-03-31
      • 2014-05-14
      • 1970-01-01
      相关资源
      最近更新 更多