简体   繁体   English

关于 c 编程和终止循环中的 break 语句

[英]About break statement in c programming and termination of a loop

I have a doubt regarding the break statement in this program.我对这个程序中的break语句有疑问。
Technically the break statement terminates the loop it is presented in, but in this program the break is inside the if statement.从技术上讲, break语句终止了它所在的循环,但在这个程序中, break位于if语句中。
So, here the break should only terminate the if statement, right?所以,这里的break应该只终止if语句,对吧? But it is also terminating the do-while statement.但它也终止了do-while语句。
Sorry if I asked something wrong.对不起,如果我问错了什么。 I am new to programming我是编程新手

#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;
}

According to the C Standard (6.8.6.3 The break statement)根据 C 标准(6.8.6.3 中断声明)

2 A break statement terminates execution of the smallest enclosing switch or iteration statement. 2 break 语句终止执行最小的封闭 switch 或迭代语句。

This break statement in this if statement这个 if 语句中的这个 break 语句

if (response !='y')
    break;

terminates execution of the enclosing for statement.终止执行封闭的 for 语句。

You may imagine its action the following way你可以想象它的动作如下

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

You may not use the break statement in an if statement if the if statement is not enclosed in an iteration or switch statement.如果 if 语句未包含在迭代或 switch 语句中,则不能在 if 语句中使用 break 语句。

The break statement is a jump statement that passes the control outside the smallest enclosing switch or iteration statement. break 语句是一个跳转语句,它将控制传递到最小的封闭 switch 或迭代语句之外。

You can use "break" statement in two state.您可以在两个 state 中使用“break”语句。

  1. In the looping在循环中
  2. In the switch-case If you use in the looping.在 switch-case 如果你在循环中使用。 When the break statement works, loop will be end.当 break 语句起作用时,循环将结束。 If you use in the switch-case.When the break statement works in the one of the cases, other cases does not work.如果在 switch-case 中使用。当 break 语句在其中一种情况下起作用时,其他情况下不起作用。 Implicitly, the loop is over, if block will not run again.隐式地,循环结束,如果块不会再次运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM